2010-06-06 66 views
1

我在我的應用程序中有以下查詢。它運行良好,但我需要它也包含與每個製造商相關的產品數量。mySQL:加入三張表 - 如何?

當前查詢:

SELECT * FROM (`manufacturers`) 
JOIN `languages` ON `manufacturers`.`lang` = `languages`.`id` 
ORDER BY `languages`.`id` asc, `id` asc 

我的產品表看起來像這樣:

id | name | manufacturerid 
0  | Product1 | 0 

回答

3
SELECT `manufacturers`.*, `languages`.*, COUNT(`products`.`id`) AS NumberOfProducts 
FROM (`manufacturers`) 
JOIN `languages` ON `manufacturers`.`lang` = `languages`.`id` 
LEFT OUTER JOIN `products` ON 
     `products`.`manufacturerid` = `manufacturers`.`manufacturerid` 
GROUP BY <Column list for manufacturers AND languages here> 
ORDER BY `languages`.`id` asc, `manufacturers`.`id` asc 
+0

我在這個標記上的標記太慢了,但又是一個選項! – 2010-06-06 16:11:16

+0

您好Martin,您能解釋一下「<製造商和語言的列表列表>」嗎? – Industrial 2010-06-06 16:46:54

+0

@Industrial因爲你只有'*'在你的選擇中,我無法知道它們是什麼。 SELECT列表中不是聚合或文字的任何內容都應在「GROUP BY」子句中。我認爲MySQL允許它們不成爲,但這會改變查詢的語義。 – 2010-06-06 17:06:18

3
select * 
from `manufacturers` m 
inner join `languages` l on m.`lang` = l.`id` 
left outer join (
    select manufacturerid, count(*) as ProductCount 
    from Products 
    group by manufacturerid 
) pc on m.id = pc.manufacturerid 
order by l.`id` asc, m.`id` asc 
+0

嗨!使用解決方案時出現以下錯誤: 錯誤號:1096未使用任何表SELECT * ORDER BY'languages'.''' asc,'manufacturerrid' asc – Industrial 2010-06-06 17:08:40

+1

發佈您的模式。 – RedFilter 2010-06-06 17:12:36

+0

沒關係OrbMan,我有一個查詢,直接導致此錯誤後運行。對不起,並且非常感謝您的幫助! – Industrial 2010-06-06 17:26:30