簡體   English   中英

MySQL 5.7 | GROUP BY | 非匯總列錯誤

[英]MySQL 5.7 | GROUP BY | Non Aggregated Column Error

我將mysql數據庫從5.6升級到5.7,並且正在修復一些引發一些錯誤的查詢。 我正在處理的查詢之一涉及帶有COALESCE的GROUP BY。

這是有效的查詢(摘要):

SELECT 
    MAX(a.id),
    a.entered,
    count(*) AS teh_count
FROM
    a
INNER JOIN
    b ON b.id = a.link_to_b_id
INNER JOIN
    c ON c.link_to_b_id = b.id
WHERE
    b.revision_id > 0
AND
    c.terminated_at = '0000-00-00 00:00:00'
AND
    a.created_at > date_sub(NOW(), INTERVAL 8 HOUR)
GROUP BY
    a.entered
ORDER BY
    teh_count DESC
LIMIT
    6;

但是我需要使用c.override進行COALESCE a。輸入,所以我嘗試了以下操作:

SELECT 
    MAX(a.id),
    a.entered,
    COALESCE(c.override, a.entered) AS appearance,
    count(*) AS teh_count
FROM
    a
INNER JOIN
    b ON b.id = a.link_to_b_id
INNER JOIN
    c ON c.link_link_to_b_id = b.id
WHERE
    b.revision_id > 0
AND
    c.terminated_at = '0000-00-00 00:00:00'
AND
    a.created_at > date_sub(NOW(), INTERVAL 8 HOUR)
GROUP BY
    a.entered
ORDER BY
    teh_count DESC
LIMIT
    6;

但是MySQL 5.7現在拋出以下錯誤: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'st_core.tuc.code_appearance_override' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'st_core.tuc.code_appearance_override' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我想我可以更改sql_mode,但是我也不太願意。 該錯誤告訴我的原因是有道理的,因為COALESCE列未聚合,因此作為測試,我用MAX對其進行了封裝,並且可以正常工作,但是對我來說似乎有點不客氣。

有沒有更優雅的解決方案?

您還應該在group by子句中a.entered ,這就是錯誤的意思。 雖然不確定為什么a.code_entered不同的列進行分組a.code_entered

您的查詢應如下所示

SELECT 
    MAX(a.id),
    a.entered,
    COALESCE(c.override, a.entered) AS appearance,
    count(*) AS teh_count
FROM
    a
INNER JOIN
    b ON b.id = a.link_to_b_id
INNER JOIN
    c ON c.link_link_to_b_id = b.id
WHERE
    b.revision_id > 0
AND
    c.terminated_at = '0000-00-00 00:00:00'
AND
    a.created_at > date_sub(NOW(), INTERVAL 8 HOUR)
GROUP BY
    a.entered,
    COALESCE(c.override, a.entered)
ORDER BY
    teh_count DESC
LIMIT
    6;

我認為您打算這樣做:

SELECT MAX(a.id),
       COALESCE(c.override, a.entered) AS appearance,
       count(*) AS the_count
FROM a INNER JOIN
     b
     ON b.id = a.link_to_b_id INNER JOIN
     c
     ON c.link_link_to_b_id = b.id
WHERE b.revision_id > 0 AND
      c.terminated_at = '0000-00-00 00:00:00' AND
      a.created_at > date_sub(NOW(), INTERVAL 8 HOUR)
GROUP BY appearance
ORDER BY the_count DESC
LIMIT 6;

這將從SELECT列表中刪除a.entered ,因此只有一列可供分組。 該列可以由GROUP BY中的表別名引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM