Alk*_*lko 1 mysql sql group-by mysql-error-1055
我试图找出而不在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;
Run Code Online (Sandbox Code Playgroud)
和表格:
支付方式:
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
Run Code Online (Sandbox Code Playgroud)
产品介绍:
id title created
==========================
1 First 2016-12-10
1 Second 2016-12-11
1 Third 2016-12-12
1 Fourth 2016-12-13
Run Code Online (Sandbox Code Playgroud)
最后的结果看起来应该是谎言:
Name Total
First 2
Second 1
Third 1
Fourth 1
Run Code Online (Sandbox Code Playgroud)
但是,如果我将查询更改为GROUP BY t.item, t.created错误消失了,但我最终得到的是五条记录而不是四条记录,这不是我想要的.由于我是根据"item"字段对项目进行分组,因此应该只有四个记录
这是您的查询:
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;
---------^
Run Code Online (Sandbox Code Playgroud)
指向的地方有问题.请注意,SELECT并且GROUP BY指的是不同的列.在a中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;
Run Code Online (Sandbox Code Playgroud)
我还要补充一点,这COUNT(t.qty)是可疑的.通常qty是指"数量",你想要的是总和: SUM(t.qty).
| 归档时间: |
|
| 查看次数: |
6079 次 |
| 最近记录: |