我有一张表: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 运算符?或任何更好的实现?
最佳答案
只需将两个 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
关于mysql - 如何在 sql 查询中替换 UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53290924/