我试图找出而不在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.created
错误消失了,但我最终得到的是五条记录而不是四条,这不是我想要的。由于我是根据“item”字段对项目进行分组,因此应该只有四个记录
答案 0 :(得分:6)
这是您的查询:
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;
---------^
指向地方有问题。请注意,SELECT
和GROUP BY
指的是不同的列。在LEFT 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)
。
答案 1 :(得分: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错误消失了”请记住,如果您使用的选定列不在组中,则从mysql 5.7开始,您有错误..
如果您确实需要,可以禁用sql模式的正确设置,例如
SET sql_mode = ''
https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
最后一列按顺序对ONLY_FULL_GROUP_BY param上的组没有影响..但是如果我按顺序排列的列不是选择有实际意义
答案 2 :(得分:0)
项目1有两个t.created
。因此,您可以决定要对哪个进行排序。 E.g:
ORDER BY MIN(t.created) DESC;