如何选择从伦敦向所有项目出售P1件的供应商?

时间:2019-07-04 17:35:09

标签: mysql sql

我有这些表:

Suppliers S (S#, name-S, Status, City)
PIECES P (P#, name-P, colour, weight, City)
PROJECTS J (J#, name-J, Ciudad)
SELLS SPJ (S#, P#, J#, quantity)

我想找到所有向伦敦的所有项目出售"p1"件商品的供应商

select PROJECTS.j
from SELLS, Suppliers, PIECES, PROJECTS 
where SELLS.s = Suppliers.s
           and  SELLS .p=PIECES .p
           and  SELLS .j=PROJECTS .j
           and PIECES .p="p1"
           and PROYECTOS.ciudad="London"

此精选的供应商只销售一个项目,但不销售所有项目

销售数据:

   supply piece project quantity   
1. s1     p1    j1       5  
2. s1     p1    j3       4  
3. s2     p1    j2       5  
4. s4     p1    j1       1  

j1和j2是伦敦的项目,S4并不出售所有项目,而是出售结果

1 个答案:

答案 0 :(得分:0)

列名甚至不允许为表加上别名,因为这样会更加混乱。
无论如何,请正确地联接4个表,在WHERE子句中设置条件,按供应商分组,最终条件在HAVING子句中:

select 
  suppliers.s, suppliers.name
from suppliers
inner join sells on sells.s = suppliers.s
inner join pieces on pieces.p = sells.p
inner join projects on projects.j = sells.j
where pieces.p = 'p1' and projects.cioudad = 'London'
group by suppliers.s, suppliers.name
having count(distinct projects.j) = (select count(*) from projects where cioudad = 'London')