简体   繁体   English

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

[英]SQL Query return extra column depending of condition

I want to make a query which will add a column depending of what condition is meet(I have tried with sequelize without obtaining the result that I wanted) therefore I want to try with plain SQL because It does not have as many limitations.我想进行一个查询,该查询将根据满足的条件添加一列(我尝试使用 sequelize 却没有获得我想要的结果)因此我想尝试使用普通的 SQL 因为它没有那么多限制。

EXAMPLE: SELECT * FROM db.messages WHERE user_id = userID OR $contacts.user_id$ = userID示例: SELECT * FROM db.messages WHERE user_id = userID OR $contacts.user_id$ = userID

If the first condition is meet I want to add a column like:如果满足第一个条件,我想添加如下列:

SELECT *,'type' as 'Inbox' FROM db.messages

Second condition:第二个条件:

SELECT *,'type' as 'Send' FROM db.messages

I have not manage to implement it with a CASE...THEN我还没有设法用CASE...THEN

I would appreciette any comment.我会欣赏任何评论。

SQL CASE STatement: SQL 案例说明:

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

The syntax for the case statement seems to be invalid, check the documentation . case 语句的语法似乎无效,请查看文档 Instead of this:而不是这个:

select
    case
        when a = x then 'a' as result
        when b = x then 'b' as result
        else null
    end as y
from table_name

Try this:尝试这个:

select
    case
        when a = x then 'a'
        when b = x then 'b'
    end as 'result'
from table_name

or even simpler:甚至更简单:

select
    case x
        when a then 'a'
        when b then 'b'
    end as 'result'
from table_name 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM