简体   繁体   中英

How to replace outer query value if subquery returns null

This is my query:

SELECT * FROM main_menu AS m WHERE EXISTS(select * from menu where menu.main_menu_id = m.main_menu_id AND menu.menu IS NOT NULL)

Above query shows rows from main_menu table only if their respective rows in menu table is not NULL, which is correct.

But I would like to do something more. If the value for menu table(subquery) found NULL , the main_menu value(outer query) should be altered,something like using IFNULL but for the outer query. How do I do that, please?

Then you should use a LEFT JOIN and not EXISTS() statement :

SELECT m.*,COALESCE(m2.<Column>,OtherValue),....
FROM main_menu m
LEFT JOIN menu m2
 ON(m2.main_menu_id = m.maid_menu_id AND m2.menu is not null)

This will join both tables even when there is no such record, and will have NULL values for all menu columns.

You didn't define 'should be altered' , so that's the best I can come up with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM