找到具有tw o或多個供應商:
select part_id
from catalog
group by part_id
having count(part_id) >= 2
找到這些部件的供應商(S),更面向未來的,可以呈現出兩個以上的供應商:
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
@wwosik:我也是,但與'或'它更可能他們可能是可選的。 –
如果我理解得很好,OP希望成對供應商提供東西X.他不希望僅由一個供應商提供的產品或不提供的產品。這就是爲什麼我刪除我的評論... – user76035
@wwosik:我增加了更多的信息,但原來。查詢將加入同一列 - 值將重複。 –