从子查询中获取总行数?

时间:2013-07-25 09:51:08

标签: mysql count subquery

我有一个像

这样的查询
SELECT row1, row2
FROM (
    SELECT b.row21, COUNT(b.row21) AS hits
    FROM table2 AS b
    WHERE b.row22 = 'foo' OR b.row22 = 'bar'
    GROUP BY b.row21
    HAVING hits = 2
) AS b
INNER JOIN table1 AS a ON (b.row21 = a.row1)
WHERE row2 = 123
LIMIT 10

现在显然,结果首先受到额外WHERE的限制,最后受到LIMIT的限制。

那么如何检索子查询返回的行数而不需要单独执行呢?

1 个答案:

答案 0 :(得分:1)

您可以使用变量在MySQL中执行此操作:

SELECT row1, row2, @rn as numrows
FROM (
    SELECT b.row21, COUNT(b.row21) AS hits, @rn := @rn + 1
    FROM table2 b cross join
         (select @rn := 0) const
    WHERE b.row22 = 'foo' OR b.row22 = 'bar'
    GROUP BY b.row21
    HAVING hits = 2
) AS b
INNER JOIN table1 AS a ON (b.row21 = a.row1)
WHERE row2 = 123
LIMIT 10;

您冒着MySQL 可以以非常不同的方式重写查询的风险,这可能会避免生成某些行。一些SQL编译器足够聪明,可以做到这一点。我不认为MySQL那么聪明。