Search code examples
mysqlsqljoinselectmysql-5.7

how to return alternative columns on join


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


Solution

  • 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