0

假设我有以下 MySQL 表:

Table  Comment:
  id int not null,
  parent_id int not null,
  body text not null,
  created datetime not null

parent_id 是递归关系。不用管它是否可以为空,因为如果没有父级,我总是可以分配一个虚拟 id。

我想为每个父母选择子评论(每个父母最近的 5 个)。

如果我使用类似的东西

SELECT * FROM Comment WHERE parent_id in (...) ORDER BY created DESC

这将为每个指定的父母选择所有评论,这是我不想要的。

我想在单个查询中或以最有效的方式选择父母以及一级子女(最多 5 个)。

任何想法?

4

2 回答 2

0

parent_id 不为空?如果我想发布一条新评论,实际上它会成为父评论?这个属性将是 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 )
于 2013-09-09T07:37:15.083 回答
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)将有助于提高效率。

于 2013-09-09T07:46:45.813 回答