我正在尝试使用SQL检索来自不同用户的每个帖子的最新消息。我有3张桌子:
但是,我的SQL语法出错了,这是代码
SELECT
MAX(sequence) AS latestmsg,
COUNT(*) AS msgcount,
sequence,
messageid,
username,
receipient,
message,
datestamp
FROM
messages
JOIN
users
ON messages.username = users.username
JOIN
posts
ON posts.postid = messages.messageid
WHERE
messages.receipient = 'try-2a'
GROUP BY
messages.messageid
ORDER BY
messages.sequence DESC
错误:字段列表中的列'用户名'不明确
答案 0 :(得分:2)
SELECT
MAX(sequence) AS latestmsg,
COUNT(*) AS msgcount,
sequence,
messageid,
users.username,
receipient,
message,
datestamp
FROM
messages
JOIN
users
ON messages.username = users.username
JOIN
posts
ON posts.postid = messages.messageid
WHERE
messages.receipient = 'try-2a'
GROUP BY
messages.messageid
ORDER BY
messages.sequence DESC
尝试以下修改过的查询:
SELECT sequence AS latestmsg,
msgcount,
sequence,
messages.messageid,
users.username,
receipient,
message,
messages.datestamp
FROM messages
JOIN users ON messages.username = users.username
JOIN posts ON posts.postid = messages.messageid
JOIN (
SELECT messageid, MAX(sequence) AS max_seq, COUNT(*) AS msgcount
FROM messages
GROUP BY messageid
) m ON m.messageid = messages.messageid AND m.max_seq = messages.sequence
WHERE messages.receipient = 'try-2a'
ORDER BY messages.sequence DESC
答案 1 :(得分:0)
username
列表中的SELECT
列需要以表格别名为前缀,因为username
和messages
都存在users
SELECT
MAX(sequence) AS latestmsg,
COUNT(*) AS msgcount,
sequence,
messageid,
username, --This column needs to have the alias prefix
receipient,
message,
datestamp
答案 2 :(得分:0)
如果您要为每个用户查找最新消息,您可能希望按用户分组,然后查找每个用户组中每条消息的最大时间戳。您可以使用它来选择与其匹配的时间戳的消息。