我有一个主题和 topic_comments 表。我想加入他们两个。
+------------+ +------------+
| Topic | | Comments |
+------------+ +------------+
| id | | parent_id |
| title | | content |
| createdate | | createdate |
| content | | creator_id |
+------------+ +------------+
加入位于 topic.id = topic_comments.parent_id
上。我想显示带有最新评论的主题,并按最新评论 createdate
排序。并且不显示重复的主题。谁能帮我吗?
到目前为止我有这个:
select p.id, p.title, p.createdate, p.content, p.int_0 as reacties_total, p.char_1 as prio, p.char_0 as status, r.createdate as r_createdate, r.creator_id as r_creator_id, r.content as r_content
from pages p, topic_reacties r
where r.parent_id = p.id
and p.parent_id = ' . $this->id . '
order by p.int_2 desc
但是,这不会显示没有评论的主题。它只返回带有反应的主题。
最佳答案
您想要显示带有最新评论并按评论排序的主题,还是显示每个主题(无论是否有评论)?这是两个不同的要求。
如果您想显示带有最新评论的主题,请像您一样使用连接(除非请丢失古老的语法),但在 on
子句中添加更多详细信息:
select p.id, p.title, p.createdate, p.content,
p.int_0 as reacties_total, p.char_1 as prio,
p.char_0 as status, r.createdate as r_createdate,
r.creator_id as r_creator_id, r.content as r_content
from pages p
join topic_reacties r
on r.parent_id = p.id
and r.createdate =(
select Max( createdate )
from topic_reacties
where parent_id = r.parent_id )
order by r.createdate;
不要让子查询吓到你。对其进行测试,如果 createdate
列已建立索引,您将看到令人印象深刻的效率。
如果您想要所有 个主题,无论它们是否有评论,但只有最新的有评论的主题,那么请使用外连接。您仍将使用相同的子查询,但某些 DBMS 不允许在外连接的 on
子句中使用子查询。以甲骨文为例。我不确定MySQL。无论如何,为了安全起见,我总是将其移至 where
子句。 (我处理很多不同的 DBMS。)
但是,当您在 where
子句中检查外部联接的外部表时,可以将输出转换为与内部联接相同。所以你必须使用一些小技巧。
select p.id, p.title, p.createdate, p.content,
p.int_0 as reacties_total, p.char_1 as prio,
p.char_0 as status, r.createdate as r_createdate,
r.creator_id as r_creator_id, r.content as r_content
from pages p
left join topic_reacties r
on r.parent_id = p.id
where (r.parent_id is null
or r.createdate =(
select Max( createdate )
from topic_reacties
where parent_id = r.parent_id ))
order by r.createdate;
请注意,我在 where
检查周围放置了圆括号/方括号,但正如所写,它们并不是绝对必要的。但是,如果您添加任何其他检查,则需要将它们放在括号之外。
where (r.parent_id is null
or r.createdate =(
select Max( createdate )
from topic_reacties
where parent_id = r.parent_id ))
and p.ID = :SomeID
查看 SQL Fiddle
关于php - MySQL 查询加入主题的最后评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29027699/