【发布时间】:2021-01-13 11:38:53
【问题描述】:
我正在编辑文本,并将原始和编辑后的文本逐句存储在两个单独的表中,如下所示:
(原件)
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 的评论被认为是最后一个。
我想要做的是从SENTENCE 表中选择引用给定url_id 的all_the_sentences,同时选择所有“最终”(如: MAX(id)) 编辑了 SENTENCE_REVIEW 表中的句子,其中句子被编辑。
如果句子没有被编辑,并且 sentence_id 不存在于 SENTENCE_REVIEW 表中,我只希望这些句子在这些列为空的情况下返回,但仍作为来自 @987654329 的值返回@表。
这最后一步是我卡住的地方。
我试过了:
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,但都无济于事。
我错过了什么?
谢谢,
【问题讨论】:
-
前两个重复,icates 是精确的(加入另一个表并从那里获取组内最大值的记录)。第三个副本一般解释了如何在组中选择具有最大值的记录。
标签: mysql join subquery left-join greatest-n-per-group