How i can import some columns from another table in Mysql if column is null?

34 Views Asked by At

How can i do so that when the nav_page is not null that it imports the page_name as nav_label and page_slug as nav_url?

I don't know a better idea to do the navigation for my site to when i fetch the navigation i always want to get the page name from the table pages in case any change is made in the name or slug of the page.

I have tried this query but doesn't work for me:

SELECT navigations.*, (CASE WHEN (navigations.nav_page IS NOT NULL) THEN pages.page_name AS page_label, pages.tr_slug AS page_url ELSE navigations.nav_label AS page_label, navigations.nav_url AS page_url END) FROM navigations, pages

Pages Table

+---------+-----------+-----------+
| page_id | page_name | page_slug |
+---------+-----------+-----------+
|       1 | Home      | /home     |
|       2 | Contact   | /contact  |
+---------+-----------+-----------+

Navigations Table

+--------+-----------+------------------------+----------+----------+
| nav_id | nav_label |        nav_url         | nav_page | nav_type |
+--------+-----------+------------------------+----------+----------+
|      1 | Google    | https://www.google.com | NULL     | custom   |
|      2 | NULL      | NULL                   | 2        | page     |
+--------+-----------+------------------------+----------+----------+
1

There are 1 best solutions below

0
On BEST ANSWER

If I follow you correctly, you can left join:

select n.nav_id,
    coalesce(p.page_slug, n.nav_url) as nav_url,
    coalesce(p.page_name, n.nav_label) as nav_label,
    n.nav_type
from navigations n
left join pages p on page_id = n.nav_page