views:

56

answers:

2

Hi everybody,

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 `manufacturers`.`lang` = `languages`.`id`
ORDER BY `languages`.`id` asc, `id` asc

My products table looks like this:

id    |    name    |    manufacturerid
0     |   Product1 |    0
+3  A: 
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 
RedFilter
Hi! I get the following error when using your solution: Error Number: 1096 No tables used SELECT * ORDER BY `languages`.`id` asc, `manufacturerid` asc
Industrial
Post your schema.
RedFilter
Never mind OrbMan, I had a query that run directly after this that caused the error. Sorry, and thanks a lot for your help!
Industrial
+2  A: 
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
Martin Smith
I was far too slow off the mark on this one but another option!
Martin Smith
Hi Martin, can you explain "<Column list for manufacturers AND languages here>" ?
Industrial
@Industrial As you only had `*` in your select I wasn't able to know what they are. Anything in the SELECT list that is not an aggregate or literal should be in the `GROUP BY` clause. I think MySQL allows them not to be but that would change the semantics of the query.
Martin Smith
Hi Martin, thanks a lot for your help!
Industrial