带有2个SELECT,UNION和LIMIT的MySQL查询 - 如何计算所有项目?

时间:2011-11-26 05:12:04

标签: mysql sql

我无法弄清楚如何计算查询结果,因为我limit输出:

(SELECT "new" as type, name FROM newUsers WHERE name LIKE '%John%')
UNION
(SELECT "old" as type, name FROM oldUsers WHERE name LIKE '%John%')
ORDER BY 1 ASC LIMIT 1, 10

我得到的最远的是SELECT COUNT(*) ( my query ) as userCount但是我没有得到我的查询输出的所有其他字段。

2 个答案:

答案 0 :(得分:2)

( select SQL_CALC_FOUND_ROWS ...)
union
( select ...) // not using SQL_CALC_FOUND_ROWS here
order by ... limit ...;

从第一个查询中获得结果后,
你可以再次查询

 select found_rows(); // to get all the rows count

来自documentation

的信息

答案 1 :(得分:1)

这可能会回答你似乎要求的信件,但这并不是制定查询的一种非常明智的方式:

SELECT c.numusers, n.type, n.name
  FROM (SELECT "new" AS type, name  FROM newUsers WHERE name LIKE '%John%') AS n
  JOIN (SELECT COUNT(*) AS numusers FROM newUsers WHERE name LIKE '%John%') AS c
UNION
SELECT c.numusers, o.type, o.name
  FROM (SELECT "old" AS type, name  FROM oldUsers WHERE name LIKE '%John%') AS o
  JOIN (SELECT COUNT(*) AS numusers FROM oldUsers WHERE name LIKE '%John%') AS c
ORDER BY 1 ASC LIMIT 1, 10

这里唯一奇怪的是两个表之间没有连接条件(既不是ON也不是USING子句)。您可能需要使用CROSS JOIN而不是(INNER)JOIN;或者,您可以向计数查询引入列"new" AS type,然后加入ON n.type = c.type。然后,您可能需要添加一个GROUP BY子句 - 在大多数DBMS中您需要它,但MySQL可能会让您在没有它的情况下逃脱。

但是,我认为您可以通过两个单独的查询做得更好 - 一个用于问题中的类型和名称,另一个用于:

SELECT COUNT(*) AS numusers, "new" AS type
  FROM newUsers
 WHERE name LIKE '%John%'
 GROUP BY type
UNION
SELECT COUNT(*) AS numusers, "old" AS type
  FROM oldUsers
 WHERE name LIKE '%John%'
 GROUP BY type;

鉴于您使用的是MySQL,您可以在第二个查询中没有GROUP BY子句的情况下离开。