mySQL:加入三张桌子 - 怎么样?

时间:2010-06-06 16:02:17

标签: php mysql join

我的申请中有以下查询。它运作良好,但我需要它还包含与每个制造商相关的产品数量。

当前查询:

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

我的产品表如下:

id    |    name    |    manufacturerid
0     |   Product1 |    0

2 个答案:

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

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