我有这个查询
SELECT
`from_id` as user_id,
MAX(`createdon`) as updated_at,
SUM(`unread`) as new,
u.username,
p.sessionid,
s.access
FROM (
SELECT `from_id`, `createdon`, `unread`
FROM `modx_messenger_messages`
WHERE `to_id` = {$id}
UNION
SELECT `to_id`, `createdon`, 0
FROM `modx_messenger_messages`
WHERE `from_id` = {$id}
ORDER BY `createdon` DESC
) as m
LEFT JOIN `modx_users` as u ON (u.id = m.from_id)
LEFT JOIN `modx_user_attributes` as p ON (p.internalKey = m.from_id)
LEFT JOIN `modx_session` as s ON (s.id = p.internalKey)
GROUP BY `from_id`
ORDER BY `new` DESC, `createdon` DESC;
表
id | message | createdon | from_id | to_id | unread
1 | test | NULL | 5 | 6 | 0
2 | test2 | NULL | 6 | 5 | 1
3 | test3 | NULL | 6 | 5 | 1
结果new
= 28.为什么?
如果正确删除加入new
= 2。
答案 0 :(得分:0)
虽然它取决于实际的数据库,但纯SQL表示使用GROUP BY的语句要求所有非聚合列都在GROUP BY中。如果不包括所有列,可能会发生奇怪的事情,这可能解释了为什么会得到不同的结果。如果您知道user_id中的其他列将是相同的,您可以执行MAX(u.username)或类似的操作(同样,取决于您的数据库服务器)。所以我首先尝试清理SQL语句。