2014-09-28 125 views
0
SELECT topics.* 
FROM topics topics 
    JOIN rh_topictags tt ON tt.topic_id = topics.topic_id 
    JOIN rh_topictags_tag t ON tt.tag_id = t.id 
    JOIN forums f ON f.forum_id = topics.forum_id 
WHERE LOWER(t.tag) IN ('super', 'fun') 
    AND f.rh_topictags_enabled = 1 
    AND topics.forum_id IN (1, 2, 3, 4) 
    AND topics.topic_visibility = 1 
GROUP BY topics.topic_id 
HAVING count(t.id) = 2 
ORDER BY topics.topic_last_post_time DESC 
LIMIT 0, 10 

如何获得整体找到的行数(没有限制)?SQL查询+限制+统计一个查询的总体结果?

我可以不是使用SELECT FOUND_ROWS()因为这个查询必须在几个DBMS(mysql,mssql,oracle,postgres,sqlite,sqlite3)下运行。

不幸的是,这并不工作:

SELECT topics.*, COUNT(topics.*) AS result_count 
FROM topics topics 
    JOIN rh_topictags tt ON tt.topic_id = topics.topic_id 
    JOIN rh_topictags_tag t ON tt.tag_id = t.id 
    JOIN forums f ON f.forum_id = topics.forum_id 
WHERE LOWER(t.tag) IN ('super', 'fun') 
    AND f.rh_topictags_enabled = 1 
    AND topics.forum_id IN (1, 2, 3, 4) 
    AND topics.topic_visibility = 1 
GROUP BY topics.topic_id 
HAVING count(t.id) = 2 
ORDER BY topics.topic_last_post_time DESC 
LIMIT 0, 10 
+0

您需要加入其中,你做的次数没有限制 – 2014-09-28 20:17:21

+0

但后来我有这个巨大的选择查询在外部查询的SELECT部分​​内查询?然后,我最好运行两个查询... – Stuck 2014-09-28 20:19:00

+1

是的,你可能应该运行两个,如果你需要限制结果..即使它在技术上可能做到一个.. – 2014-09-28 20:22:23

回答

0

这个怎么样:

Select * 
from 
( 
    SELECT topics.*, count(*) as result_count 
    FROM topics topics 
     JOIN rh_topictags tt ON tt.topic_id = topics.topic_id 
     JOIN rh_topictags_tag t ON tt.tag_id = t.id 
     JOIN forums f ON f.forum_id = topics.forum_id 
    WHERE LOWER(t.tag) IN ('super', 'fun') 
     AND f.rh_topictags_enabled = 1 
     AND topics.forum_id IN (1, 2, 3, 4) 
     AND topics.topic_visibility = 1 
    GROUP BY topics.topic_id 
    HAVING count(t.id) = 2 
) a 
ORDER BY a.topic_last_post_time DESC 
LIMIT 0, 10 
+0

这给我4结果,每个结果都有result_count = 1(应该是4,因为有4个结果) – Stuck 2014-09-28 20:37:13

+0

所以如果你只运行内部查询,你会得到'result_count = 4'吗?并且是4的完整计数 - 它不是明确的问题.. – Milen 2014-09-28 20:40:34

+0

不,result_count = 1为内部查询 – Stuck 2014-09-28 20:41:11