通过从 MySQL 中的其中一个中选择 MAX(different_key) 在特定键上连接 2 个表

Joining 2 tables on a specific key with selecting MAX(different_key) from one of them in MySQL

我正在编辑文本,并将原始文本和编辑文本逐句存储在两个单独的 table 中,如下所示:

(原件)

SENTENCE
id (auto increment, primary)
url_id (refers to the URL of given copy)
sentence (longtext)

(审阅副本)

SENTENCE_REVIEW
id (auto increment, primary)
sentence_id (this should refer to the id in the SENTENCE table)
url_id (see as before - this might be redundant here, but that's not important for now)
sentence_review (longtext)

这个想法是任何给定的句子都可以有无限数量的评论,最高 SENTENCE_REVIEW.id 的评论被认为是最后的评论。

我想要做的是 select all_the_sentences 从 [=16= 引用给定的 url_id ] table 同时 select 所有“最终”(如:MAX(id))编辑了来自 SENTENCE_REVIEW table 的句子,这些句子是已编辑。

如果句子没有被编辑,sentence_idSENTENCE_REVIEWtable中不存在,我只想让那些句子和那些栏目一起回来空,但仍作为 SENTENCE table.

中的值返回

这是我卡住的最后一步。

我试过了:

SELECT sentence.id, sentence.url_id, sentence_review.sentence_id, sentence, MAX(sentence_review.id), sentence_review FROM sentence   
LEFT OUTER JOIN sentence_review
ON sentence.id = sentence_review.sentence_id
GROUP BY sentence_review.sentence_id
ORDER BY sentence.id

返回的是所有经过编辑的句子的所有“最终”版本,而不是未经编辑的句子。 JOIN 能想到的各种办法都试过了,都没用。

我错过了什么?

谢谢,

你想带上每句话的最新评论。一个选项使用 left join 和 window 函数:

select s.*, sr.sentence_review
from sentence s
left join (
    select sr.*, row_number() over(partition by sentence_id order by id desc) rn
    from sentence_review sr
) sr on sr.sentence_id = s.sentence_id and s.rn = 1

但这需要 MySQL 8.0。在早期版本中,您可以使用相关子查询进行过滤:

select s.*, sr.sentence_review
from sentence s
left join sentence_review sr 
    on  sr.sentence_id = s.sentence_id
    and sr.id = (
        select max(sr1.id)
        from sentence_review sr1
        where sr1.sentence_id = sr.sentence_id
    )