2013-02-19 162 views
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個記錄和其在connector表,該表中supplierdata_iddata表的id相等的記錄COUNT()

的結果應該是這樣的:

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

我怎麼能做到這一點,在MySQL的一個查詢?

+1

RTLM:http://en.wikipedia.org/wiki/Join_%28SQL%29 – 2013-02-19 15:44:22

+0

@GordonLinoff我拖查詢嘗試,我想知道有沒有辦法在短短一個查詢寫道: ?! – MajAfy 2013-02-19 15:47:04

回答

1
​​
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 
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)