说我有以下MySQL表:
Table Comment:
id int not null,
parent_id int not null,
body text not null,
created datetime not null
parent_id是递归关系。不管它是否可以为空,因为如果没有父母,我总是可以分配一个虚拟身份。
我想为每个家长选择子评论(每个家长最近5次)。
如果我使用
之类的东西SELECT * FROM Comment WHERE parent_id in (...) ORDER BY created DESC
这将为每个指定的父级选择所有注释,这是我不想要的。
我想选择父母和一年级儿童(最多5个) 在单个查询中或以最有效的方式。
任何想法?
答案 0 :(得分:0)
parent_id不是null?如果我想要一个帖子新评论,实际上它将成为家长评论?这个属性是0还是什么?
我想,我不会探究这句话:
select * from comment as c where c.id=NUMBER and c.parent_id in (Select id from comment as c2 where c.parent_id = c2.id )
答案 1 :(得分:0)
SELECT p.*
FROM Comment AS p
WHERE id IN (...) -- list of parent IDs
UNION ALL
SELECT
c.*
FROM
( SELECT id AS parent_id
FROM Comment
WHERE id IN (...) -- list of parent IDs
) AS d
JOIN
Comment AS c
ON c.parent_id = d.parent_id
AND c.created >= COALESCE(
( SELECT ci.created
FROM Comment AS ci
WHERE ci.parent_id = d.parent_id
ORDER BY ci.created DESC
LIMIT 1 OFFSET 4
), '1000-01-01')
ORDER BY
COALESCE(parent_id, id),
c.created ;
(parent_id, created)
上的索引有助于提高效率。