SQLITE查询连接两个具有不同条件的相同表

时间:2016-04-02 16:38:33

标签: mysql sql-server sqlite

我有一个名为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并显示结果,如下面的列;

  1. sender/recipient的唯一值 10208819391147662
  2. message之间的最后sender/recipient 10208819391147662 AND sender/recipient 10208819391147662 }。
  3. 第二个timestamp(消息)。
  4. 为了实现以下目标,我有这个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。但是使用MAXGroup 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了。任何建议都表示赞赏。

1 个答案:

答案 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中效果很好。