【问题标题】:How to select only if the last element of an inner-join matches?仅当内部连接的最后一个元素匹配时如何选择?
【发布时间】:2021-09-14 10:27:44
【问题描述】:

我有两张桌子:processesnotes。每个注释都链接到一个过程。一个进程有几个注释(一对多关系)。笔记也有创建日期。

我想选择最后一个注释包含特定文本(例如“某些内容”)的每个进程,但前提是此注释是该进程的最后一个创建的注释。

例如:

进程表:

id | name
----------
42 | 'foo'

笔记表:

content       | creation_date | process_id
-------------------------------------------
'note1'       | '09/13'       | 42
'note1'       | '09/14'       | 42
'some_content'| '09/15'       | 42

notes 中的 process_id 字段是外键。在此示例中,我的查询应选择“foo”进程。

如果添加新注释,notes 表格将变为如下所示:

content       | creation_date | process_id
-------------------------------------------
'note1'       | '09/13'       | 42
'note1'       | '09/14'       | 42
'some_content'| '09/15'       | 42
'note4'       | '09/16'       | 42

在这种情况下,不应选择“foo”进程,因为最后一个注释内容不再是“some_content”。

是否有可能在单个查询中完成这样的事情?

我正在使用 MySQL。

【问题讨论】:

  • 您希望联接对注释 1 和某些内容起作用,而不是对注释 4 起作用?为什么会这样?
  • 这里的模式是什么,因为 some_content 也与您希望加入工作的注释 1 不同?
  • edit您的问题向我们展示您的两个表的 SHOW CREATE TABLE 的输出。而且,2022 年 1 月 1 日应该发生什么?
  • 你在使用 MySQL > 8 吗?

标签: mysql sql inner-join


【解决方案1】:

一种可能性是聚合:

select p.id, p.name
from processes p join
     notes n
     on n.process_id = p.id
group by p.id, p.name
having max(n.creation_date) = max(case when n.note like '%some_content%' then n.creation_date end);

【讨论】:

    【解决方案2】:

    您可以像这样使用相关子查询:

    SELECT *
    FROM processes
    WHERE (
        SELECT content
        FROM notes
        WHERE notes.process_id = processes.id
        ORDER BY creation_date DESC
        LIMIT 1
    ) = 'some_content'
    

    【讨论】:

      【解决方案3】:

      另一种方法只是使用exists

      select * 
      from processes p
      where exists (
          select * from notes n
          where n.process_id=p.id 
              and n.content='some_content' 
              and n.creation_date=(select Max(creation_date) from notes)
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-30
        • 1970-01-01
        • 2020-07-03
        • 2016-06-01
        • 2017-11-28
        相关资源
        最近更新 更多