![](/img/trans.png)
[英]IF (SUBQUERY) = SOMETHING SELECT A ELSE SELECT B MySql
[英]How to achiave this:MYSQL SELECT if true select a else select b?
我想選擇user.*
如果chat.chat_type IS NULL
,但如果chat.chat_type = 1
我要選擇組。*
SELECT
CASE
WHEN chat.chat_type IS NULL THEN user.*
WHEN chat.chat_type =1 THEN group.*
END,
x,y
FROM `chat` LEFT JOIN group ...
我該如何實現?
您必須使用Union:
SELECT user.* from user join ... where chat.chat_type is null
Union
SELECT `Group`.* from `Group` join .... where chat.chat_type =1
如果用戶和組的列數不同,則必須在列數較少的地方使用默認值。
提示:因為組是關鍵字,所以您應該重命名表
所描述的數據庫設計不是很好,因為您的聊天表中有一個ID,可以是用戶ID或組ID。 因此,您不能在此列上具有約束(外鍵),這使得可以在其中放置任何值,即,甚至不存在的ID。
無論如何,在給定設計的前提下,要使用戶或用戶組在您已經提到的條件下外部連接兩個表。 然后使用COALESCE
查看結果行中是否有用戶或組。
select c.from, coalesce(u.name, g.name) as to_name
from chat c
left join usr u on c.chat_type is null and c.to = u.user_id
left join grp g on c.chat_type = 1 and c.to = g.group_id
where c.chat_type is null or c.chat_type = 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.