查询左联接获取数据问题-MySQL

时间:2020-09-01 16:50:39

标签: mysql sql

我用左联接联接两个表。当我选择全选时,所有行都会出现(查询1)。但是,当我使用select拉一些行时,仅加载一个数据,而不是加载图1中的所有数据。是什么原因?

query1 query2

加载所有数据查询1

查询1:

SELECT * 
FROM oc_review AS OYLAMA 
JOIN oc_product AS PRODUCT 
    ON (PRODUCT.product_id = OYLAMA.product_id)
INNER JOIN oc_product_to_category AS KATEGORI 
    ON (KATEGORI.product_id = PRODUCT.product_id) 
WHERE KATEGORI.category_id = 69

仅加载1个数据查询2

查询2:

SELECT
    AVG(ALL OYLAMA.rating) AS ORTALAMA,
    COUNT(OYLAMA.rating) AS TOPLAMOY 
FROM oc_review AS OYLAMA 
JOIN oc_product AS PRODUCT
    ON (PRODUCT.product_id = OYLAMA.product_id) 
INNER JOIN oc_product_to_category AS KATEGORI
    ON (KATEGORI.product_id = PRODUCT.product_id) 
WHERE KATEGORI.category_id = 69

1 个答案:

答案 0 :(得分:2)

MySQL创建一个单一的组,在您引入诸如AVG()COUNT()之类的汇总函数后,所有记录都将放入其中。另请参见问题MySQL Aggregate Functions without GROUP BY clause

您可能想做的是明确指定一个GROUP BY子句,并将GROUP BY之后的字段也添加到SELECT中,例如:

SELECT 
   PRODUCT.product_id, 
   AVG(ALL OYLAMA.rating) AS ORTALAMA,
   COUNT(OYLAMA.rating) AS TOPLAMOY 
FROM oc_review AS OYLAMA 
JOIN oc_product AS PRODUCT 
   ON(PRODUCT.product_id = OYLAMA.product_id) 
INNER JOIN oc_product_to_category AS KATEGORI 
   ON (KATEGORI.product_id = PRODUCT.product_id) 
WHERE KATEGORI.category_id = 69
GROUP BY PRODUCT.product_id