sql查询+限制+计数整体结果在一个查询?

时间:2014-09-28 20:15:23

标签: mysql sql

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

如何获取总体找到的行数(没有限制)?

我可以使用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

1 个答案:

答案 0 :(得分: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