4

我试图在不禁用 my.ini 中的“only_full_group_by”的情况下弄清楚

这是我的查询:

SELECT 
  p.title,
  COUNT(t.qty) AS total 
FROM
  payments t 
  LEFT JOIN products AS p 
    ON p.id = t.item 
WHERE t.user = 1 
GROUP BY t.item
ORDER BY t.created DESC;

和表格:

付款:

id     item   user   created
============================
1      1      1      2017-01-10
2      2      1      2017-01-11
3      3      1      2017-01-12
4      4      1      2017-01-13
5      1      1      2017-01-14

产品:

id     title    created
==========================
1      First     2016-12-10
1      Second    2016-12-11
1      Third     2016-12-12
1      Fourth    2016-12-13

最终结果应该看起来是谎言:

Name    Total
First   2
Second  1
Third   1
Fourth  1

但是,如果我将查询更改为GROUP BY t.item, t.createdError 消失了,但我最终得到了 5 条记录而不是 4 条记录,这不是我想要的。由于我根据“项目”字段对项目进行分组,因此应该只有四条记录

4

3 回答 3

11

这是您的查询:

SELECT p.title, COUNT(t.qty) AS total 
-------^
FROM payments t LEFT JOIN
     products AS p 
     ON p.id = t.item 
WHERE t.user = 1 
GROUP BY t.item
---------^
ORDER BY t.created DESC;
---------^

指出的地方有问题。请注意,SELECTandGROUP BY指的是不同的列。在 aLEFT JOIN中,您(几乎)总是希望按第一个表中的某些内容进行聚合,而不是第二个。

ORDER BY是另一个问题。您没有按此列进行汇总,因此您需要确定您想要的值。我猜MIN()MAX()

SELECT p.title, COUNT(t.qty) AS total 
FROM payments t LEFT JOIN
     products AS p 
     ON p.id = t.item 
WHERE t.user = 1 
GROUP BY p.title
ORDER BY MAX(t.created) DESC;

我还要补充一点,这COUNT(t.qty)是可疑的。通常qty是指“数量”,您想要的是总和: SUM(t.qty).

于 2017-02-05T20:40:01.937 回答
1

第 1 项有两个t.created。因此请决定要按哪个排序。例如:

ORDER BY MIN(t.created) DESC;
于 2017-02-05T20:22:21.830 回答
0

对我来说,您应该按 p.title 分组查询

  SELECT 
    p.title,
    COUNT(t.qty) AS total 
  FROM
    payments t 
    LEFT JOIN products AS p 
      ON p.id = t.item 
  WHERE t.user = 1 
  GROUP BY p.title;

或者

  SELECT 
    p.title,
    COUNT(t.qty) AS total 
  FROM
    payments t 
    LEFT JOIN products AS p 
      ON p.id = t.item 
  WHERE t.user = 1 
  GROUP BY p.title
  order by p.created;

然后对于“但是如果我将查询更改为 GROUP BY t.item,t.created 错误就消失了”请记住,如果您使用未在 group by 中的选定列,则从 mysql 5.7 开始会出现错误..

如果你真的需要,你可以禁用使用适当的 sql 模式设置,例如

SET sql_mode = ''   

https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html

最后按顺序排列的列对 group by 和 ONLY_FULL_GROUP_BY 参数没有影响 .. 但如果我按顺序排列的列不在 select 中几乎没有意义

于 2017-02-05T19:56:00.747 回答