繁体   English   中英

sql查询+限制+在一个查询中计算总体结果?

[英]sql query + limit + count overall results in one query?

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

那这个呢:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM