gpt4 book ai didi

mysql - 如何实现这个:MYSQL SELECT if true select a else select b?

转载 作者:行者123 更新时间:2023-11-29 20:05:41 28 4
gpt4 key购买 nike

如果chat.chat_type IS NULL,我想选择user.*,但如果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 ...

我怎样才能实现这个目标?

最佳答案

所描述的数据库设计不太好,因为聊天表中有一个 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;

关于mysql - 如何实现这个:MYSQL SELECT if true select a else select b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40355880/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com