【问题标题】:MySQL conditional where clause if element present in joinMySQL 条件 where 子句如果元素存在于连接中
【发布时间】:2022-12-05 13:20:40
【问题描述】:

讯息

id hash recipient created_at
1 hsxarfcdup_12 example1@test.com 2022-01-01
2 hsxarfcdup_12 example1@test.com 2022-01-01
3 huudbnjjewo67 example3@test.com 2022-01-01
4 poimzgdyundkh example4@test.com 2022-01-01

链接

id hash created_at
1 huudbnjjewo67 2022-01-01
2 poimzgdyundkh 2022-01-01

我有 2 张桌子。消息表存储发送给每个收件人的消息。它有一个列hash,每批发送的消息都可以相同。

另一个表links可以与该表链接。所以我的情况是根据列hashlinks左加入messages

所以我真正想要的是使用links.created_at,如果它存在于加入后的结果集中,如果不存在,我想使用messages.created_at

这样的事情可能吗?

【问题讨论】:

    标签: php mysql


    【解决方案1】:
    SELECT ...
    FROM messages
    LEFT OUTER JOIN links USING (hash)
    WHERE COALESCE(hash.created_at, messages.created_at) > ?
    

    不幸的是,这将无法使用索引进行优化,因为任何索引只能在一个表上。

    您可以通过执行两个查询并将它们与 UNION 组合来优化它:

    SELECT ...
    FROM messages
    INNER JOIN links USING (hash)
    WHERE hash.created_at > ?
    UNION
    SELECT ...
    FROM messages
    LEFT OUTER JOIN links USING (hash)
    WHERE hash.id IS NULL AND messages.created_at > ?
    

    【讨论】:

      猜你喜欢
      • 2014-03-08
      • 2012-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 2011-01-12
      • 2017-06-28
      • 1970-01-01
      相关资源
      最近更新 更多