开发者

mySQL: Joining three tables - how?

开发者 https://www.devze.com 2023-01-03 00:00 出处:网络
I have the following query in my application. It works well, but I need it to also contain the number of products that are associated with each manufacturer.

I have the following query in my application. It works well, but I need it to also contain the number of products that are associated with each manufacturer.

The current query:

SELECT * FROM (`manufacturers`)
JOIN `languages` ON `m开发者_高级运维anufacturers`.`lang` = `languages`.`id`
ORDER BY `languages`.`id` asc, `id` asc

My products table looks like this:

id    |    name    |    manufacturerid
0     |   Product1 |    0


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


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

精彩评论

暂无评论...
验证码 换一张
取 消