代码之家  ›  专栏  ›  技术社区  ›  RV.

如何在sql查询中替换UNION

  •  1
  • RV.  · 技术社区  · 6 年前

    我有一张桌子: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运算符?还是有更好的实施?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Nick SamSmith1986    6 年前

    两个都放 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

        2
  •  0
  •   Jordan Soltman    6 年前

    很容易。只用 or .

    select id,name, code, attribute, amount
    from attb
    where (code = 123 and attribute='Alpha') OR code = 122
    
        3
  •  0
  •   Ashif Nataliya    6 年前

    试试这个。

    select id,name, code, attribute, amount
        from attb
        where ((code = 123 and attribute='Alpha') or (code = 122))
    
        4
  •  0
  •   4b0 Agit    4 年前
    select id,name, code, attribute, amount
    from attb
    where (code IN(122, 123) and attribute='Alpha') ;