查找有两个或多个供应商的零件:
select part_id
from catalog
group by part_id
having count(part_id) >= 2
查找这些零件的供应商,更具前瞻性,可以显示两个或多个供应商:
select c.part_id, s.supplier_name
from catalog c
join supplier s
where c.part_id in (
select part_id
from catalog
group by part_id
having count(part_id) >= 2)
order by c.part_id, s.supplier_name
但是如果您想要只有两个供应商的零件:
select c.part_id, group_concat(s.supplier_name) as suppliers
from catalog c
join supplier s using(supplier_id)
where part_id in (
select part_id
from catalog
group by part_id
having count(part_id) = 2)
group by c.part_id
如果您只希望这两个供应商在两列中显示..我也在想... :-)
[更新]
我想到了什么:
select c.part_id, c.min(c.supplier_id) as first, c.max(c.supplier_id) as second
from catalog c
join supplier s
where c.part_id in (
select part_id
from catalog
group by part_id
having count(part_id) = 2)
group by c.part_id
order by c.part_id
获取供应商名称:
select x.part_id, a.supplier_name, b.supplier_name from
(
select c.part_id, c.min(c.supplier_id) as first, c.max(c.supplier_id) as second
from catalog c
join supplier s
where c.part_id in (
select part_id
from catalog
group by part_id
having count(part_id) = 2)
group by c.part_id
order by c.part_id
) as x
join supplier a on x.first = a.sid
join supplier b on x.second = b.sid