Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why COUNT(*) of multiple rows of SELECT 1 is always 1?

Tags:

sql

mysql

SELECT COUNT(*) FROM (

SELECT 1 FROM ... 
UNION SELECT 1 FROM ...
UNION SELECT 1 FROM ...

) as tmp_table

Despite the result set including multiple rows, COUNT(*) will always return 1... why?

like image 291
Helmut Avatar asked Jan 15 '23 21:01

Helmut


1 Answers

UNION SELECT automatically groups your results, meaning that you will not see duplicate rows. What you need is UNION ALL SELECT..., then your results will not be grouped and you will see duplicate rows.

Duplicate rows meaning, because you always select 1, so it groups by 1.

like image 123
Chris Avatar answered Jan 30 '23 18:01

Chris