如何解决通过在MySQL中从其中一个选择MAXdifferent_key来连接特定键上的2个表
我正在编辑文本,并将原始文本和编辑后的文本逐句存储在两个单独的表中,如下所示:
(原始副本)
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的评论将被认为是最后一个。
我想做的是从url_id
表中选择引用给定SENTENCE
的 all_the_entents ,同时选择所有“最终” (例如:MAX(id)
)在SENTENCE_REVIEW
表中编辑句子的地方。
如果句子没有被编辑,并且sentence_id
表中不存在SENTENCE_REVIEW
,我只希望这些句子返回时这些列为空,但仍然返回为值SENTENCE
表中。
这是我受阻的最后一步。
我尝试过:
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
和窗口函数:
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
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。