Akim Prestatic
Akim Prestatic

Reputation: 134

SELECT and Count in INNER JOIN

I try to display, the number of images of each product. but here is the request returns me the number of images of all the products.

SELECT images, pl.*, l.iso_code, ps.price, cl.name as category_name
FROM `ps_product_lang` pl
INNER JOIN `ps_product` p ON (p.`id_product` = pl.`id_product`)
INNER JOIN `ps_lang` l ON (pl.`id_lang` = l.`id_lang`)
INNER JOIN `ps_product_shop` ps ON (ps.`id_product` = p.`id_product`)
INNER JOIN `ps_category_lang` cl ON (cl.`id_category` = p.`id_category_default`) and (cl.`id_lang` = pl.`id_lang`)
 
INNER JOIN (SELECT id_image, id_product, COUNT(id_image) AS images
FROM `ps_image`) i ON (i.`id_product` = p.id_product)
 
WHERE p.active = 1 AND cl.id_shop = 1
ORDER BY pl.name ASC
LIMIT 10 OFFSET 0

at this line.

INNER JOIN (SELECT id_image, id_product, COUNT(id_image) AS images
FROM `ps_image`) i ON (i.`id_product` = p.id_product)

code sql https://www.sexy-charmes.fr/sql.sql

Upvotes: 1

Views: 369

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269693

This query is malformed:

(SELECT id_image, id_product, COUNT(id_image) AS images
 FROM ps_image
) 

It is bad SQL and should be rejected with a syntax error. Happily, MySQL now does that with the default settings.

What is the problem? You have an aggregation query because of the COUNT(). There is no GROUP BY, so the query returns exactly one row. But those rows also have "bare" columns. That is a SQL syntax error and an error in almost all databases.

You really only want to aggregate by one column. That should be the only column select without an aggregation function and it should be in the GROUP BY:

(SELECT id_product, COUNT(id_image) AS images
 FROM ps_image
 GROUP BY id_product
) 

Upvotes: 5

Related Questions