首页 > 解决方案 > 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;

标签: mysqlsqlsequelize.js

解决方案


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 

推荐阅读