我有一个名为messages
的SQL表,其中包含以下详细信息;
id, sender, recipient, message, timestamp
"1","10204456572654160","10208819391147662","Hi.. : What are you up to?","1459541723279"
"2","10204456572654160","10208819391147662","Got my test message?","1459541749818"
"3","10208819391147662","10204456572654160","This is my message","1459611679108"
"4","10208819391147662","10204456572654160","And another message","1459611735455"
"5","10204456572654160","10208819391147662","And I reply like this","1459611758570"
"6","10153775515332771","10208819391147662","It's me.. Syco !!","1459611900348"
"7","10153775515332771","10208819391147662","You there?","1459611900350"
"8","10208819391147662","10153775515332771","Yes.. What's upp..","1459611900380"
"9","10204464403169266","10208819391147662","How're you doin?","1459612000666"
现在,我想将一个值传递给我的函数e.g. 10208819391147662
并显示结果,如下面的列;
sender/recipient
的唯一值不 10208819391147662
message
之间的最后sender/recipient
不 10208819391147662
AND sender/recipient
10208819391147662
}。timestamp
(消息)。为了实现以下目标,我有这个sql;
SELECT s1.*, max(c2.message), max(c2.timestamp)
FROM (
SELECT sender as username
FROM messages
WHERE sender <> '10208819391147662'
UNION
SELECT recipient as username
FROM messages
WHERE recipient <> '10208819391147662'
) s1
LEFT JOIN messages c2 ON (s1.username = c2.sender OR s1.username = c2.recipient)
GROUP BY s1.username
我已成功使用1st column
提取UNION
。但是使用MAX
和Group by
子句在第2和第3位没有运气。
我的最终预期结果应该是;
username, message, timestamp
"10204456572654160","And I reply like this","1459611758570"
"10153775515332771","Yes.. What's upp..","1459611900380"
"10204464403169266","How're you doin?","1459612000666"
到目前为止我的SQLFiddle了。任何建议都表示赞赏。
答案 0 :(得分:0)
实际上,最后这是我的最终SQL,它完成了我想要的东西。
SELECT c2.id, s1.username, c2.message, max(c2.timestamp)
FROM (
SELECT sender as username
FROM messages
WHERE sender <> '10208819391147662'
UNION
SELECT recipient as username
FROM messages
WHERE recipient <> '10208819391147662'
) s1
LEFT JOIN messages c2 ON (s1.username = c2.sender OR s1.username = c2.recipient)
GROUP BY s1.username
ORDER BY timestamp DESC
但不知何故,在SQLFiddle中,这在MYSQL
中无法正常工作,但在SQLITE
中效果很好。