简体   繁体   English

MySQL Join Query(可能有两个内连接)

[英]MySQL Join Query (possible two inner joins)

I currently have the following: 我目前有以下内容:

Table Town: 表镇:

  • id ID
  • name 名称
  • region 区域

Table Supplier: 表供应商:

  • id ID
  • name 名称
  • town_id town_id

The below query returns the number of suppliers for each town: 以下查询返回每个城镇的供应商数量:

SELECT t.id, t.name, count(s.id) as NumSupplier
FROM Town t 
INNER JOIN Suppliers s ON s.town_id = t.id 
GROUP BY t.id, t.name

I now wish to introduce another table in to the query, Supplier_vehicles. 我现在想在查询中引入另一个表,Supplier_vehicles。 A supplier can have many vehicles: 供应商可以有很多车辆:

Table Supplier_vehicles: Table Supplier_vehicles:

  • id ID
  • supplier_id supplier_id
  • vehicle_id vehicle_id

Now, the NumSupplier field needs to return the number of suppliers for each town that have any of the given vehicle_id (IN condition): 现在,NumSupplier字段需要返回具有任何给定vehicle_id(IN条件)的每个城镇的供应商数量:

The following query will simply bring back the suppliers that have any of the given vehicle_id: 以下查询将简单地带回具有任何给定vehicle_id的供应商:

SELECT * FROM Supplier s, Supplier_vehicles v WHERE s.id = v.supplier_id AND v.vehicle_id IN (1, 4, 6)

I need to integrate this in to the first query so that it returns the number of suppliers that have any of the given vehicle_id. 我需要将其集成到第一个查询中,以便返回具有任何给定vehicle_id的供应商数量。

SELECT t.id, t.name, count(s.id) as NumSupplier
FROM Town t 
INNER JOIN Suppliers s ON s.town_id = t.id 
WHERE s.id IN (SELECT sv.supplier_id
               FROM supplier_vehicles sv 
               WHERE sv.vehicle_id IN (1,4,6))
GROUP BY t.id, t.name

Or you could do an INNER JOIN (as your supplier join is INNER, but this will remove towns with no suppliers with those vehicles) and change the COUNT(s.id) TO COUNT(DISTINCT s.id) 或者您可以进行内部INNER JOIN (因为您的供应商加入是INNER,但这将删除那些没有供应商的城镇)并将COUNT(s.id)更改为COUNT(DISTINCT s.id)

If I remember correctly, you can put your second query inside the LEFT OUTER JOIN condition. 如果我没记错的话,你可以把你的第二个查询放在LEFT OUTER JOIN条件下。

So for example, you can do something like 例如,你可以做类似的事情

... LEFT OUTER JOIN (SELECT * FROM Suppler s, Supplier_vehicles ......) s ON s.town_id=t.id ... LEFT OUTER JOIN(SELECT * FROM Suppler s,Supplier_vehicles ......)s ON s.town_id = t.id

In that way you are "integrating" or combining the two queries into one. 通过这种方式,您可以将两个查询“集成”或组合成一个查询。 Let me know if this works. 让我知道这个是否奏效。

SELECT t.name, count(s.id) as NumSupplier
FROM Town t
LEFT OUTER JOIN Suppliers s ON t.id = s.town_id
LEFT OUTER JOIN Supplier_vehicles v ON s.id = v.supplier_id
WHERE v.vehicle_id IN (1,4,6)
GROUP BY t.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM