mysql - SQL 查询根据条件返回额外的列
问题描述
我想进行一个查询,该查询将根据满足的条件添加一列(我尝试使用 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 语句的语法似乎无效,请查看文档。而不是这个:
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
推荐阅读
- google-sheets - 将公式复制到 A 列的最后一行(在表格中)
- javascript - 获取 json 文件时出现 GET - 404(未找到)错误
- angular - 直接从 html 中调用 Angular 组件的函数会破坏单元测试
- azure - 在 blob 存储中转换 xslx csv 文件并存储到 ADLS
- database - 如何开始数据输入、记录和绘图程序?(我可能会移植到一个网站)
- tensorflow - 微调后如何评估 Huggingface 模型?
- docker - 如何在 HPC 集群上运行奇异容器?- 错误:创建用户命名空间失败:用户命名空间已禁用
- reactjs - 无法读取未定义的属性(读取“updateProfile”)
- cpu - 假设 64 位计数器不会溢出是否安全?
- python - 为配置屏幕中的每个设置调用不同方法的 Pythonic 方式