【发布时间】:2021-02-10 18:31:25
【问题描述】:
这是这个问题的小提琴:http://sqlfiddle.com/#!9/0569eb/1
我有一个 cmets 表,回复存储在同一个表中,如下所示。
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(6) unsigned NOT NULL,
`parent` int(3) unsigned NOT NULL,
`posted_by` int(3) unsigned NOT NULL,
`comment` varchar(200) NOT NULL,
`sort` int(3) NOT NULL,
PRIMARY KEY (`id`),
INDEX (`parent`),
INDEX (`posted_by`),
INDEX (`sort`)
) DEFAULT CHARSET=utf8;
INSERT INTO `comments` (`id`, `parent`, `posted_by`, `comment`, `sort`) VALUES
('1', '0', '1', 'Here is a comment by user 1', '5'),
('2', '1', '2', 'Here is a reply by user 2', '5'),
('3', '1', '3', 'Here is a reply by user 3', '5'),
('4', '1', '2', 'Here is a reply by user 2', '5'),
('5', '0', '2', 'Here is a comment by user 2', '2'),
('6', '0', '5', 'Here is a comment by user 5', '3');
我需要能够选择用户发布的主要 cmets,或者让同一用户发布回复。以下是我想出的为用户 2 获取适当数据的方法。
由于一条评论可以有多个回复,因此我在子查询中使用 DISTINCT 以每行仅获得一个回复。这是一个合适的解决方案,还是有更好的方法来处理这种情况?
SELECT
c.id,
c.comment
FROM comments c
LEFT JOIN (SELECT DISTINCT comments.parent FROM comments WHERE comments.posted_by = 2) r ON r.parent = c.id
WHERE
(
c.posted_by = 2
OR r.parent IS NOT NULL
)
AND c.parent=0
ORDER BY c.sort DESC;
以下是与用户 2 相关的 cmets 的预期输出
【问题讨论】:
-
不聚合的分组方式与选择不同的方式相同。 PS请在考虑发布问题之前进行研究。如果您想优化、学习和应用基础知识并报告发现,这表明没有研究。特别是阅读索引的基础知识。 PS 索引默认顺序是升序。
-
您好,您能否根据您提供的数据发布您预期的输出行。
-
@MarkB 当然!更新了我的问题。
-
请use text, not images/links, for text--including tables & ERDs。转述或引用其他文本。只提供您需要的东西并将其与您的问题联系起来。仅将图像用于无法表达为文本或增强文本的内容。在图像中包含图例/键和说明。 PS minimal reproducible example PS 当没有重复行时,x join y where c or d is x join y where c union x join y where d。你可以谷歌重新那个。 (了解有关使用“站点:”进行谷歌搜索的信息。) PS 通常,工程中没有“最佳”,请根据您的情况进行衡量。 PS 研究?
-
不清楚您所说的“这种情况”究竟是什么意思。这个特殊的代码?哪一部分?从某种意义上说是这样的代码......?