Mysql 聚合函数与查询中的某列冲突
我有两张桌子:Mysql 聚合函数与查询中的某列冲突,mysql,group-by,aggregate-functions,Mysql,Group By,Aggregate Functions,我有两张桌子: users: ___________________________ |user_id | username | |_______________|___________| | 1 | Dolly | | 2 | Didi | |_______________|___________| forum: _______________________________________________
users:
___________________________
|user_id | username |
|_______________|___________|
| 1 | Dolly |
| 2 | Didi |
|_______________|___________|
forum:
_____________________________________________________________
|match_static_id| comment | timpstamp | user_id |
|_______________|___________|______________________|__________|
| 1 | Hi | 2013-07-10 12:15:03 | 2 |
| 1 | Hello | 2013-07-09 12:14:44 | 1 |
|_______________|___________|______________________|__________|
SELECT forum.match_static_id,
count(forum.match_static_id) 'comments_no', max(forum.timestamp)'timestamp', users.username
FROM forum
INNER JOIN users on users.id = forum.user_id
GROUP BY forum.match_static_id
此查询工作正常,仅使用thw论坛
表:
SELECT forum.match_static_id,
count(forum.match_static_id) 'comments_no', max(forum.timestamp)'timestamp'
FROM forum
GROUP BY forum.match_static_id
Order BY timestamp DESC
但以下查询使用两个表:
users:
___________________________
|user_id | username |
|_______________|___________|
| 1 | Dolly |
| 2 | Didi |
|_______________|___________|
forum:
_____________________________________________________________
|match_static_id| comment | timpstamp | user_id |
|_______________|___________|______________________|__________|
| 1 | Hi | 2013-07-10 12:15:03 | 2 |
| 1 | Hello | 2013-07-09 12:14:44 | 1 |
|_______________|___________|______________________|__________|
SELECT forum.match_static_id,
count(forum.match_static_id) 'comments_no', max(forum.timestamp)'timestamp', users.username
FROM forum
INNER JOIN users on users.id = forum.user_id
GROUP BY forum.match_static_id
在这里,我想得到max(timestamp)的用户,但我得到了错误的用户。任何人都能给我一个关于这个的线索吗?
按时间戳顺序描述尝试以下操作:
SELECT f1.match_static_id,
f2.comments_no,
f2.maxtimestamp,
users.username
FROM forum AS f1
INNER JOIN
(
SELECT match_static_id,
max(timestamp) maxtimestamp,
count(comment) AS comments_no
FROM Forum
GROUP BY match_static_id
) AS f2 ON f1.match_static_id = f2.match_static_id
AND f1.timestamp = f2.maxtimestamp
INNER JOIN users on users.user_id = f1.user_id;
请在此处查看它的实际操作:
max(时间戳)
foreach匹配\u static\u id
还是什么?关于users.username
您希望为每个分组的match\u static\u id
选择哪个用户名?我希望注释的用户名为max(时间戳)。这是一个常见问题解答,但如果您看到演示,comment\u no字段给出的是1,它应该是2。我需要max timestamp的用户,但我也需要注释\u noaffected@BaselShbeb-啊哈,好的,对不起,请看我的编辑。从内部查询中选择它。