用一个查询选择记录

时间:2013-02-19 15:43:17

标签: mysql sql join count

这些是我的表结构:

数据:

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()表中connector所有data_id表中的supplier条记录和id条记录的所有列data表的id | name | COUNT() ------+-----------+--------- 1 | d1 | 2 2 | d2 | 1 3 | d3 | 0

结果应该是这样的:

{{1}}

如何在mySQL中使用一个查询执行此操作?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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)