假设我有一个名为mytable
:
+-----+-----+-----------+
|ID | ID2 | product |
+-----+-----+-----------+
| 1 | 1 | product1 |
| 2 | 2 | product1 |
| 3 | 1 | product2 |
| 4 | 4 | product2 |
| 5 | 1 | product3 |
| 6 | 1 | product4 |
| 7 | 4 | product4 |
+-----+-----+-----------+
我想选择所有拥有的产品,id2 = 4
如果没有,请id2 = 4
显示id2 = 1
。
输出应为:
id product
1 product1
4 product2
5 product3
7 product4
我可以在SQL中做这样的事情吗(我正在使用mysql)?
另一个使用条件聚合来选择产品且id对应于id2 = 4或id2 = 2的查询
select coalesce(
max(case when id2=4 then id end),
max(case when id2=1 then id end)
) id,
product
from mytable
where id2 in (4,1)
group by product
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句