简体   繁体   English

SQL-将要查找的结果包含在列中,并将所有其他值设置为null

[英]SQL - include results you are looking for in a column and set all other values to null

I have two tables, one with orders and another with order comments. 我有两个表,一个带有订单,另一个带有订单注释。 I want to join these two tables. 我想加入这两个表。 They are joined on a column "EID" which exists in both tables. 它们连接在两个表中都存在的列“ EID”上。 I want all orders. 我要所有订单。 I also want to see all comments with only certain criteria AND all other comments should be set to null. 我还希望仅使用特定条件查看所有评论,而所有其他评论应设置为null。 How do I go about this? 我该怎么办?

Orders Table 订单表
Order_Number 订单号
1 1个
2 2
3 3
4 4

Comments Table 评论表
Comments 评论
Cancelled On 已取消
Ordered On 订购于
Cancelled On 已取消
Cancelled On 已取消

In this example I would like to see for my results: 在此示例中,我希望看到我的结果:

Order_Number | 订单号| Comments 评论
1 | 1 | Cancelled On 已取消
2 | 2 | Null 空值
3 | 3 | Cancelled On 已取消
4 | 4 | Cancelled On 已取消

Thanks! 谢谢!

This seems like a rather trivial left join. 这似乎是一个相当琐碎的左联接。

select o.order_number, c.comments
  from orders o
left join comments c
    on o.eid = c.eid
    and (here goes your criteria for comments)

Tested on Oracle, there might be subtle syntax differences for other DB engines. 在Oracle上进行了测试,其他DB引擎可能存在细微的语法差异。

It depends on one condition: Are you trying to SET the other comments to null? 这取决于一个条件:您是否正在尝试将其他注释设置为null? (replace the values in the table) or Are you trying to DISPLAY the other comments as null? (替换表中的值)或您是否试图将其他注释显示为null? (dont display them) (不要显示它们)

If you want to change the values in the table use 如果要更改表中的值,请使用

    UPDATE `table` SET `column` = null WHERE condition;

otherwise use: 否则使用:

    SELECT column FROM table JOIN othertable WHERE condition;

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

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