我希望该表返回最多2个回复从每个主题使用右连接。我可以知道我该怎么做吗?
Topic table
+--------+
| tid |
+--------+
| 1 |
| 2 |
| 3 |
| 4 |
+--------+
Reply table
+--------+--------+
| rid | tid |
+--------+--------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 2 |
| 7 | 4 |
| 8 | 4 |
| 9 | 4 |
+--------+--------+
Result
+--------+--------+
| tid | rid |
+--------+--------+
| 1 | 1 |
| 1 | 2 |
| 2 | 4 |
| 2 | 5 |
| 3 | null |
| 4 | 7 |
| 4 | 8 |
+--------+--------+发布于 2015-11-02 13:02:54
下面这个Top-N查询如何:
select tid, rid from(
select t.tid, r.rid,
case when @tid is not null and @tid != t.tid then @rn := 0 else null end reset_rn,
@tid := t.tid tid_change,
@rn := @rn + 1 rn
from topic t
left join reply r on t.tid = r.tid
join (select @rn := 0, @tid := null) rn
order by t.tid, r.rid
) q
where rn < 3;保留哪两行的关键是内部查询中的order by。
https://stackoverflow.com/questions/33470661
复制相似问题