我想订购"联系"表格由" contactreply"表。 " contactid"排在" contactreply" table是" ID"排在"联系人"表。 "联系"必须通过表格中的最后一个插入来排序" contactreply" " contactid"是" ID"在表格中"联系"。
联系表:
+----+--------+----------+----------+
| ID | userid | subject | content |
+----+--------+----------+----------+
| 1 | 1 | subject | subject |
| 2 | 1 | subject2 | subject2 |
+----+--------+----------+----------+
回复表
+----+--------+-----------+---------+
| ID | userid | contactid | content |
+----+--------+-----------+---------+
| 1 | 1 | 1 | reply1 |
| 2 | 1 | 2 | reply2 |
| 3 | 1 | 1 | fasd |
| 4 | 1 | 2 | asdf |
| 5 | 1 | 2 | f |
| 6 | 1 | 1 | asdf |
+----+--------+-----------+---------+
我尽力解释它并希望你理解它;) 我已经看过其他帖子,但我无法让它发挥作用。
提前谢谢。
答案 0 :(得分:1)
检查这是否符合预期
select a.*, b.id from contact as a
inner join
(select * from contactReply as x
where x.id =
(select max(id) from contactReply as y
where x.contactid = y.contactid)
) as b
on a.ID = b.contactId
order by b.id
答案 1 :(得分:1)
SELECT c.*
FROM contacts c
JOIN reply x
ON x.contactid = c.id
JOIN
( SELECT MAX(id) max_id FROM reply GROUP BY contactid ) y
ON y.max_id = x.id
ORDER
BY x.id;
+----+--------+----------+----------+
| ID | userid | subject | content |
+----+--------+----------+----------+
| 2 | 1 | subject2 | subject2 |
| 1 | 1 | subject | subject |
+----+--------+----------+----------+