仅当内部联接的最后一个元素匹配时如何 select?
How to select only if the last element of an inner-join matches?
我有两个 table:processes
和 notes
。每个笔记都链接到一个过程。一个过程有几个注释(一对多关系)。笔记也有创建日期。
我想 select 每个进程的最后一个注释包含特定文本(比如 'some content'),但前提是此注释是该进程的最后一个创建的。
例如:
进程table:
id | name
----------
42 | 'foo'
备注table:
content | creation_date | process_id
-------------------------------------------
'note1' | '09/13' | 42
'note1' | '09/14' | 42
'some_content'| '09/15' | 42
notes
中的 process_id
字段是一个外键。在此示例中,'foo' 进程应由我的查询 select 编辑。
如果添加了新的注释,notes
tables 会变成这样:
content | creation_date | process_id
-------------------------------------------
'note1' | '09/13' | 42
'note1' | '09/14' | 42
'some_content'| '09/15' | 42
'note4' | '09/16' | 42
在这种情况下,不应 'foo' 处理 select,因为最后的注释内容不再是 'some_content'。
是否可以在单个查询中完成这样的事情?
我正在使用 MySQL。
您可以像这样使用相关子查询:
SELECT *
FROM processes
WHERE (
SELECT content
FROM notes
WHERE notes.process_id = processes.id
ORDER BY creation_date DESC
LIMIT 1
) = 'some_content'
一种可能是聚合:
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);
另一种方法只是使用 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)
)
我有两个 table:processes
和 notes
。每个笔记都链接到一个过程。一个过程有几个注释(一对多关系)。笔记也有创建日期。
我想 select 每个进程的最后一个注释包含特定文本(比如 'some content'),但前提是此注释是该进程的最后一个创建的。
例如:
进程table:
id | name
----------
42 | 'foo'
备注table:
content | creation_date | process_id
-------------------------------------------
'note1' | '09/13' | 42
'note1' | '09/14' | 42
'some_content'| '09/15' | 42
notes
中的 process_id
字段是一个外键。在此示例中,'foo' 进程应由我的查询 select 编辑。
如果添加了新的注释,notes
tables 会变成这样:
content | creation_date | process_id
-------------------------------------------
'note1' | '09/13' | 42
'note1' | '09/14' | 42
'some_content'| '09/15' | 42
'note4' | '09/16' | 42
在这种情况下,不应 'foo' 处理 select,因为最后的注释内容不再是 'some_content'。
是否可以在单个查询中完成这样的事情?
我正在使用 MySQL。
您可以像这样使用相关子查询:
SELECT *
FROM processes
WHERE (
SELECT content
FROM notes
WHERE notes.process_id = processes.id
ORDER BY creation_date DESC
LIMIT 1
) = 'some_content'
一种可能是聚合:
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);
另一种方法只是使用 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)
)