gpt4 book ai didi

mysql - SQL查询根据条件返回额外的列

转载 作者:行者123 更新时间:2023-12-03 22:24:49 26 4
gpt4 key购买 nike

我想做一个查询,它将根据满足什么条件添加一列(我尝试使用 sequelize 没有获得我想要的结果)因此我想尝试使用纯 SQL,因为它没有那么多限制。
例子:SELECT * FROM db.messages WHERE user_id = userID OR $contacts.user_id$ = userID如果满足第一个条件,我想添加一个列,如:SELECT *,'type' as 'Inbox' FROM db.messages第二个条件:SELECT *,'type' as 'Send' FROM db.messages我还没有设法用 CASE...THEN 实现它
我会很感激任何评论。
SQL CASE 语句:

SELECT *,
CASE
WHEN user_id = userID THEN 'Inbox'
WHEN $contacts.user_id$ = userID THEN 'Send'
ELSE NULL
END AS type
FROM db.messages;

最佳答案

case 语句的语法似乎无效,请检查 the documentation 。取而代之的是:

select
case
when a = x then 'a' as result
when b = x then 'b' as result
else null
end as y
from table_name
试试这个:
select
case
when a = x then 'a'
when b = x then 'b'
end as 'result'
from table_name
甚至更简单:
select
case x
when a then 'a'
when b then 'b'
end as 'result'
from table_name

关于mysql - SQL查询根据条件返回额外的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65467900/

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