如何通过多重内部联接进行分组依据

时间:2019-06-14 07:56:59

标签: mysql sql

我尝试使用内部联接对选定数据进行过滤 我有3张桌子我应该加入 这是我的查询

SELECT DISTINCT *
FROM products_products
    INNER JOIN products_products_translations on products_products.id = products_products_translations.entry_id
    INNER JOIN products_products_related on products_products.id = products_products_related.entry_id
    INNER JOIN upload_files on products_products_related.related_id = upload_files.related_id
WHERE products_products_translations.locale = 'tr'
GROUP BY products_products_related.entry_id;


这就是我得到的错误

  

查询1错误:SELECT列表的表达式#35不在GROUP BY子句中,并且包含未聚合的列   “ shop.products_products_translations.id”在功能上不起作用   取决于GROUP BY子句中的列;这与   sql_mode = only_full_group_by

2 个答案:

答案 0 :(得分:1)

删除distinct,然后添加products_products_related.entry_id, COUNT(*)

SELECT products_products_related.entry_id, COUNT(*)
FROM products_products
         INNER JOIN products_products_translations on products_products.id = products_products_translations.entry_id
         INNER JOIN products_products_related on products_products.id = products_products_related.entry_id
         INNER JOIN upload_files on products_products_related.related_id = upload_files.related_id
WHERE products_products_translations.locale = 'tr'
GROUP BY products_products_related.entry_id;

答案 1 :(得分:0)

您不能直接选择不位于group by子句后面的列。

原因是当您按任意列(例如entry_id)分组时,每个entry_id都只有一行。但是,每个entry_id在原始表中都有很多行,其他列中有很多不同的值。

因此,您需要告诉查询如何聚合不是您决定分组依据的列的列。

您可以通过COUNT(...)或SUM(...)或许多其他功能来汇总它们。

解决方案如下:

SELECT products_products_related.entry_id, MAX(Column1), MIN(Column2) /*etc...*/
FROM products_products
    INNER JOIN products_products_translations on products_products.id = products_products_translations.entry_id
    INNER JOIN products_products_related on products_products.id = products_products_related.entry_id
    INNER JOIN upload_files on products_products_related.related_id = upload_files.related_id
WHERE products_products_translations.locale = 'tr'
GROUP BY products_products_related.entry_id;