简体   繁体   English

INNER JOIN 中的 SELECT 和 Count

[英]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代码 sql https://www.sexy-charmes.fr/sql.sql

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.这是错误的SQL,应该因语法错误而被拒绝。 Happily, MySQL now does that with the default settings.令人高兴的是,MySQL 现在使用默认设置做到了这一点。

What is the problem?问题是什么? You have an aggregation query because of the COUNT() .由于COUNT()您有一个聚合查询。 There is no GROUP BY , so the query returns exactly one row.没有GROUP BY ,因此查询只返回一行。 But those rows also have "bare" columns.但这些行也有“裸”列。 That is a SQL syntax error and an error in almost all databases.这是一个 SQL 语法错误,并且几乎在所有数据库中都是一个错误。

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 :那应该是唯一没有聚合函数的列选择,它应该在GROUP BY

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM