SQL 根据条件查询 return 额外的列
SQL Query return extra column depending of condition
我想做一个查询,它会根据满足的条件添加一列(我已经尝试使用 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 案例说明:
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
我想做一个查询,它会根据满足的条件添加一列(我已经尝试使用 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 案例说明:
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