how to return alternative columns on join

三世轮回 提交于 2020-05-17 06:58:05

问题


I have a table with a list of functionalities for my site. Say it has three columns:

id_usr - url - landing_page
1        a.php  a.html
2        b.php  b.html
3        c.php  c.html
4        d.php  d.html

Then I have a table where for each user i have those functionalities he can display:

id_usr - func
1         1
1         3

My query selects those functionalities that the user is allowed to see and returns their url. So with the sample data it returns

a.php, c.php

And this is correct. The query is:

SELECT titolo, descr1,descr2, url, url_opz
FROM `funzioni` JOIN funz_abilitate ON funz_abilitate.id_funzione=id
WHERE funz_abilitate.id_user = $id

I am wondering how to improve my query to return the landing page for the functionalities that are not authorized. So the result should be:

a.php, b.html, c.php, d.html

So for those pages that are not in range for the user, instead of url, return the value of the landing_page column.

How do I go on this with mysql 5.7? Edited to make the columns more readible


回答1:


You could use a left join and then use a case expression to check if the page is allowed or not:

SELECT    f.id, CASE WHEN id_user IS NOT NULL THEN url ELSE landing_page END
FROM      funzioni f
LEFT JOIN funz_abilitate fa ON fa.id_funzione = f.id AND fa.id_user = $id


来源:https://stackoverflow.com/questions/61030486/how-to-return-alternative-columns-on-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!