【发布时间】:2011-10-16 02:21:06
【问题描述】:
此查询返回论坛问题/答案及其嵌套的 cmets(类似于 StackOverflow 范例)。
SELECT forum_qa.*,
user_profiles.*,
c.*,
n.pid,
v.*,
Ifnull(n.ans_count, 0) AS ans_count
FROM forum_qa
JOIN user_profiles
ON user_id = forum_qa_author_id
LEFT JOIN (SELECT *
FROM votes) AS v
ON forum_qa_id = v.forum_qa_id_fk
LEFT JOIN (SELECT forum_cm_id,
forum_cm_author_id,
forum_qa_id_fk,
forum_cm_text,
forum_cm_timestamp,
forum_cm_flag,
first_name AS forum_cm_first_name,
last_name AS forum_cm_last_name,
facebook_id AS forum_cm_fb_id,
picture AS forum_cm_picture,
moderator AS forum_cm_moderator
FROM forum_cm
JOIN user_profiles
ON user_id = forum_cm_author_id) AS c
ON forum_qa_id = c.forum_qa_id_fk
LEFT JOIN (SELECT forum_qa_parent_id AS pid,
COUNT(*) AS ans_count
FROM forum_qa
WHERE forum_qa_parent_id IS NOT NULL
GROUP BY forum_qa_parent_id) AS n
ON forum_qa_id = n.pid
WHERE forum_qa_id LIKE "%"
AND forum_qa_parent_id IS NULL
ORDER BY forum_qa_timestamp DESC
LIMIT 0,3
我正在尝试对结果进行分页并遇到以下问题:
通过在查询末尾放置 LIMIT,我最终限制了 total 行的数量,而不是问题/答案的数量。
例如,最后一行的LIMIT 0,3 给了我(qa:问题/答案;cm:评论):
forum_qa_id qa_text forum_cm_id cm_text
1 asd
2 wer 4 this is a comment
2 wer 5 this is another comment
而不是
forum_qa_id qa_text forum_cm_id cm_text
1 asd
2 wer 4 this is a comment
2 wer 5 this is another comment
3 zxc
3 zxc 7 yet another comment
任何建议如何修改我的查询以使LIMIT 0,3 返回不是 3 行,而是 3 个问题,无论有多少嵌套 cmets?
根据@michael 的建议进行更改
SELECT qa.*,
user_profiles.*,
c.*,
n.pid,
v.*,
Ifnull(n.ans_count, 0) AS ans_count
FROM (SELECT * FROM forum_qa LIMIT 0, 3) qa
JOIN user_profiles
ON user_id = qa.forum_qa_author_id
LEFT JOIN (SELECT *
FROM votes) AS v
ON qa.forum_qa_id = v.forum_qa_id_fk
LEFT JOIN (SELECT forum_cm_id,
forum_cm_author_id,
forum_qa_id_fk,
forum_cm_text,
forum_cm_timestamp,
forum_cm_flag,
first_name AS forum_cm_first_name,
last_name AS forum_cm_last_name,
facebook_id AS forum_cm_fb_id,
picture AS forum_cm_picture,
moderator AS forum_cm_moderator
FROM forum_cm
JOIN user_profiles
ON user_id = forum_cm_author_id) AS c
ON qa.forum_qa_id = c.forum_qa_id_fk
LEFT JOIN (SELECT forum_qa_parent_id AS pid,
COUNT(*) AS ans_count
FROM forum_qa
WHERE forum_qa_parent_id IS NOT NULL
GROUP BY forum_qa_parent_id) AS n
ON qa.forum_qa_id = n.pid
WHERE qa.forum_qa_id LIKE "%"
AND qa.forum_qa_parent_id IS NULL
ORDER BY qa.forum_qa_timestamp DESC
(希望)解决方案
看完这里
http://www.mysqlperformanceblog.com/2006/09/01/order-by-limit-performance-optimization/
我决定为我想要ORDER BY (forum_qa_type) 的字段编制索引——一旦我这样做了,查询就会返回正确数量的问题。
感谢@Michael 提供帮助。如果这停止工作,将在此处更新。
【问题讨论】:
-
刚刚注意到你编辑了这个。仅针对
user_profiles的单一联接可以获得多少行? -
嘿,迈克尔,看看我放在“短版”下的新信息。这令人难以置信。
-
在
qa子查询中加入明确的ORDER BY:ORDER BY something LIMIT 0,3 -
返回 2 个问题
-
而且 form_qa_author_id 永远不会为 NULL?另外,把
LIKE '%'拿出来进行调试。