【问题标题】:SQLITE query to join two of same tables with different conditionsSQLITE查询以连接两个具有不同条件的相同表
【发布时间】:2016-07-22 10:00:56
【问题描述】:

我有一个名为 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 的唯一值 NOT 10208819391147662
  2. sender/recipient 之间的最后一个 messageNOT 10208819391147662 AND sender/recipient10208819391147662
  3. 第二个(消息)的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

我已经使用UNION 成功提取了1st column。但是使用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。任何建议表示赞赏。

【问题讨论】:

  • 您需要改写问题。其中一些很难阅读,即The last message between sender/recipient which is NOT 10208819391147662 AND sender/recipient which is 10208819391147662. 你能写一个段落来解释数据是什么以及你正在尝试做什么,即给出要求而不是部分实现。
  • 请正确使用标签。 mysqlsql-serversqlite
  • 你需要 MAX 做什么?
  • @CL。我想得到sender/recipient10208819391147662之间的最后一个messagetimestamp

标签: mysql sql-server sqlite


【解决方案1】:

其实,最后这是我完成我想要的最终 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 中运行良好。

【讨论】:

  • SQLite 保证其他列来自与 MAX() 匹配的同一行。 MySQL 从某个随机行返回列值;其他数据库完全禁止这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2013-12-23
  • 1970-01-01
相关资源
最近更新 更多