找到具有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:我增加了更多的信息,但原来。查询将加入同一列 - 值将重复。 –