【问题标题】:SQL query to select all unique tuples选择所有唯一元组的 SQL 查询
【发布时间】:2019-01-23 19:16:50
【问题描述】:

我有以下数据:

现在我要做的是获取所有唯一行(按 created_at 排序),其中 source_account_id 和 target_account_id 是唯一的,并且源或目标的最新行 == 1

我已经尝试过了,但它应该返回 4 行,而它应该基本上只返回 2 行:

select
    *
from
    messages
where
    source_account_id = 1 OR target_account_id = 1
group by
    source_account_id,
    target_account_id

我期望的结果是 2 行,message_id = 3, 6。

总而言之,我真的想要 account_id = 1 的最新行(消息)以及他发送或接收消息的任何人

有什么想法吗?

【问题讨论】:

  • 不,因为在我的情况下,我不知道源和目标是哪种方式
  • 不完全是,你看 (source_account_id, target_account_id) [1,2] 和 [2,1] 对我来说是一样的。但在这种情况下,我应该返回 1,2 之间最新的行。我基本上想获取 account_id = 1(发送或接收)的所有行并获取最新的
  • @user1009698 - 您能否为数据提供CREATE TABLEINSERT INTO 命令。避免将数据发布为屏幕截图。
  • 你运行的是 MySQL 还是 sqlite ?您标记了两者,但它们是不同的 RDBMS。

标签: sql sqlite


【解决方案1】:

我认为您可以根据需要使用相关子查询::

select m.*
from messages m
where m.created_at = (select max(m2.created_at)
                      from messages m2
                      where (m2.source_account_id = m.source_account_id and
                             m2.target_account_id = m.target_account_id
                            ) or
                            (m2.source_account_id = m.target_account_id and
                             m2.target_account_id = m.source_account_id
                            )
                     ) and
      1 in (m.source_account_id, m.target_account_id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2011-12-03
    相关资源
    最近更新 更多