假设我有一个名为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
http://sqlfiddle.com/#!9/47050/1
为此,您可以使用OR
.在这种情况下,它应该有效,因为如果您满足第一个条件,您就感到满意。如果你不这样做,你会回到第二个。如果您仍然没有满足它,那么它就不会包括在内。试试这个:
SELECT DISTINCT product
FROM myTable
WHERE id2 = 4 OR id2 = 1;
编辑
这不会选择 id,但我不确定您要如何选择 id。如果一个产品有两次id2=4
怎么办?您会选择哪个id
值?如果这不能解决您的整个问题,请告诉我,我将尽力帮助制定完整的解决方案。
使用 union all
和 not exists
:
select *
from mytable
where id2 = 4
union all
select *
from mytable t
where not exists (select 1
from mytable t2
where t2.product = t.product and t2.id2 = 4)
and t.id2 = 1;
SELECT id, product
FROM (
SELECT
id, product
,case id2 when 4 then 0
when 1 then 1
end as preference
FROM
products) as t
ORDER BY t.preference