【问题标题】:How to replace UNION in sql query如何在sql查询中替换UNION
【发布时间】:2019-04-16 20:55:20
【问题描述】:

我有一张桌子:attb

------------------------------------------------
Id | Name | Code | Attribute | Amount 
------------------------------------------------
1  | AV   | 123  | Alpha     | 233
------------------------------------------------
2  | TV   | 122  | Beta      | 235
------------------------------------------------
3  | TV   | 123  | Gama      | 238
------------------------------------------------
4  | CD   | 122  | Beta      | 239
------------------------------------------------
5  | TP   | 122  | Beta      | 240
------------------------------------------------
6  | RX   | 123  | Alpha     | 241
------------------------------------------------

我将其查询为:

select id,name, code, attribute, amount
from attb
where code = 123 and attribute='Alpha'
UNION
select id,name, code, attribute, amount
from attb
where code = 122;

它返回以下内容


Id | Name | Code | Attribute | Amount 
------------------------------------------------
1  | AV   | 123  | Alpha     | 233
------------------------------------------------
2  | TV   | 122  | Beta      | 235
------------------------------------------------
4  | CD   | 122  | Beta      | 239
------------------------------------------------
5  | TP   | 122  | Beta      | 240
------------------------------------------------
6  | RX   | 123  | Alpha     | 241
------------------------------------------------

有没有一种方法可以组合两个查询而不是使用 UNION 运算符?还是有更好的实现?

【问题讨论】:

    标签: mysql sql oracle sybase


    【解决方案1】:
    select id,name, code, attribute, amount
    from attb
    where (code IN(122, 123) and attribute='Alpha') ;
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。 How to Answer
    【解决方案2】:

    试试这个。

    select id,name, code, attribute, amount
        from attb
        where ((code = 123 and attribute='Alpha') or (code = 122))
    

    【讨论】:

      【解决方案3】:

      很容易。只需使用or

      select id,name, code, attribute, amount
      from attb
      where (code = 123 and attribute='Alpha') OR code = 122
      

      【讨论】:

        【解决方案4】:

        只需将两个where 子句放入一个查询中:

        select id,name, code, attribute, amount
        from attb
        where (code = 123 and attribute='Alpha') 
           or code = 122;
        

        输出:

        id  name  code  attribute  amount
        1   AV    123   Alpha      233 
        2   TV    122   Beta       235 
        4   CD    122   Beta       239 
        5   TP    122   Beta       240 
        6   RX    123   Alpha      241 
        

        SQLFiddle demo

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-20
          • 1970-01-01
          • 2018-06-08
          • 2012-06-18
          相关资源
          最近更新 更多