简体   繁体   中英

MySQL query with 2 SELECTs, UNION and LIMIT - how to count all items?

I can't figure out how to count results from my query because I limit the output:

(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

The farthest I got was to do SELECT COUNT(*) ( my query ) as userCount but then I don't get all other fields that were outputted by my query.

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

After getting result from the first query,
you can query again

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

The info from documentation

This would probably answer the letter of what you seem to be asking for, but isn't a very sensible way to formulate the query:

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

The only oddity here is that there is no join condition (neither an ON nor a USING clause) between the two tables. You might need to use a CROSS JOIN instead of an (INNER) JOIN; alternatively, you can introduce a column "new" AS type to the count query, and join ON n.type = c.type . You might then need to add a GROUP BY clause - in most DBMS you would need it, but MySQL may let you get away without it.

However, I think you would do better with two separate queries - one for the type and name as in your question, and the other as:

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;

Given that you are using MySQL, you may be able to get away without the GROUP BY clauses in the second query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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