我试图仅限制父行。 我有那个查询
SELECT
comment.id user_id,
comment.comment,
comment.reply_id reply_id,
comment.user_id,
u.image image,
u.group gg2,
comment.edited,
comment.deleted,
u.id idd2,
g.verified verified,
comment.date,
u.login,
comment.news_id
FROM (SELECT c.*
FROM comments AS c
WHERE c.news_id = 16
ORDER BY c.id DESC
LIMIT 0, 15) AS base
LEFT JOIN comments AS comment ON (
comment.reply_id = base.id
OR comment.id = base.id
)
LEFT JOIN users u ON comment.user_id = u.id
LEFT JOIN groups g ON u.group = g.id
ORDER BY comment.id DESC
我想只限制父母而不是孩子。
此查询有效但不是最佳。 我有400万行,这个查询需要105.1980秒。
我在reply_id,id,user_id和news_id上有索引。 你可以帮助我,优化它吗?
示例LIMIT 4 parent(reply_id):
+-------------+----------------------+----------+
| id | comment | reply_id |
+-------------+----------------------+----------+
| 1 | Sample Text | 0 |
| 2 | Sample Text | 0 |
| 3 | Sample Text | 0 |
| 4 | Sample Text | 0 |
| 5 | Sample Text | 1 |
| 6 | Sample Text | 1 |
| 7 | Sample Text | 4 |
| 8 | Sample Text | 2 |
| 9 | Sample Text | 3 |
| 10 | Sample Text | 3 |
+-------------+----------------------+----------+
答案 0 :(得分:0)
限制这一点不会让它变得更快:在comment_id上的顺序是(一)你的性能限制因素。
添加限制:
SELECT
comment.id user_id,
comment.comment,
comment.reply_id reply_id,
comment.user_id,
u.image image,
u.group gg2,
comment.edited,
comment.deleted,
u.id idd2,
g.verified verified,
comment.date,
u.login,
comment.news_id
FROM (SELECT c.*
FROM comments AS c
WHERE c.news_id = 16
ORDER BY c.id DESC
LIMIT 0, 15) AS base
LEFT JOIN comments AS comment FORCE INDEX (idx_comment_nn_1) ON
comment.reply_id = base.id
OR comment.id = base.id
LEFT JOIN users u ON comment.user_id = u.id
LEFT JOIN groups g ON u.group = g.id
ORDER BY comment.id DESC
LIMIT 1;
添加此索引可能会更快一点:
CREATE INDEX idx_comment_nn_1 ON comments(id DESC);
解释计划必须告诉你它是否被使用。