2 つ以上のサプライヤーの部品を検索:
select part_id
from catalog
group by part_id
having count(part_id) >= 2
それらの部品のサプライヤーを見つけて、より将来性のある、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
ただし、正確に2つのサプライヤーしか持たない部品が必要な場合:
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
これらの 2 つのサプライヤーのみを 2 つの列に表示したい場合.. 私も考えています... :-)
[アップデート]
私が考えたこと:
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