0

这些是我的表格结构:

数据 :

id   | name
-----+-------
1    | d1
2    | d2
3    | d3

供应商 :

id   |  data_id    |  name
-----+-------------+----------
1    | 1           | Microsot
2    | 1           | Google
3    | 1           | Yahoo
4    | 2           | Apple

连接器 :

id   |  supplier_id   |  name
-----+----------------+-----------
1    | 2              | Test 1
2    | 1              | Test 2
3    | 4              | Test 3

现在我想选择所有data记录列和表中与表中相同的COUNT()记录列。connectordata_idsupplieriddata

结果应该是这样的:

id    |   name    | COUNT()
------+-----------+---------
1     | d1        | 2
2     | d2        | 1
3     | d3        | 0

如何使用 mySQL 中的一个查询来做到这一点?

4

3 回答 3

2
select data.id, data.name, count(*)
  from data 
  join supplier on supplier.data_id = data.id
  join connector on connector.supplier_id  = supplier.id
  group by data.id, data.name
于 2013-02-19T15:46:41.587 回答
1
SELECT
   data.id,
   data.name,
   COUNT(DISTINCT connector.id)
FROM
   data
   LEFT JOIN supplier ON (data.id = supplier.data_id)
   LEFT JOIN connector ON (supplier.id = connector.supplier_id)
GROUP BY
   data.id, data.name
于 2013-02-19T15:46:20.687 回答
0

像这样的东西?

SELECT data.id, data.name, COUNT(data.id) FROM data LEFT OUTER JOIN supplier ON(data.id == supplier.data_id) LEFT OUTER JOIN JOIN connector ON (supplier.id == connector.supplier_id)

于 2013-02-19T15:48:04.993 回答