![](/img/trans.png)
[英]mysql - php - Need to get only the latest record from a self referencing data
[英]Mysql get latest row of self referencing relationship
我有一個評論表,允許人們編輯他們的評論。 我沒有覆蓋評論,而是創建了一條新評論,並將其與“父母”相關聯。 另外,我將子信息添加到父級。
id, user_id, comment_id__parent, comment_id__child, comment, created_dt
現在我的問題是我想得到特定用戶的所有評論,但只有評論的最新更新。
這讓我頭疼不已,我非常感謝你的投入!
如果你的小提琴是正確的,你應該能夠這樣做:
SELECT * FROM comments
WHERE comment_id__child IS NULL AND user_id=1;
如果在編輯時總是在comment_id__child
填充'parent'注釋,則此方法有效。
對於uer_id = 1
select * from comments where user_id=1 order by created_dt desc;
這很完美! 你可以在你的sql小提琴中看到結果。
select * from comments group by user_id having count(id) = 1
UNION
select * from comments where user_id in (select user_id from comments group by user_id having count(id) > 1) and comment_id__child is null and comment_id__parent is not null;
我想我找到了一個解決方案:
SELECT *
FROM comments
WHERE user_id = 1
AND ( (comment_id__parent IS NULL
AND comment_id__child IS NULL)
OR (comment_id__parent IS NOT NULL
AND comment_id__child IS NULL) )
ORDER BY created_dt DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.