Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql UNION result has less rows than sum of table row counts

I'm using UNION to get all names in different tables.
my tables has about 10000 rows all together.
but the query returns 468 rows!!
My query is:

SELECT name FROM `shopping` 
UNION 
SELECT name FROM stores 
UNION 
SELECT name FROM concert 
UNION 
SELECT val AS name FROM event 
UNION 
SELECT name FROM fastfood

Where is the problem?

like image 288
Ariyan Avatar asked Sep 24 '12 21:09

Ariyan


People also ask

How do I count rows in union SQL?

Here is the query to count on the union query. mysql> select count(*) as UnionCount from -> ( -> select distinct UserId from union_Table1 -> union -> select distinct UserId from union_Table2 -> )tbl1; The following is the output displaying the count.

Why union all is faster than union?

Because the UNION ALL operator does not remove duplicate rows, it runs faster than the UNION operator.

Which is better union or union all?

The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all the rows from all the tables fitting your query specifics and combines them into a table. A UNION statement effectively does a SELECT DISTINCT on the results set.

What is the biggest difference between union and union all?

The only difference between Union and Union All is that Union extracts the rows that are being specified in the query while Union All extracts all the rows including the duplicates (repeated values) from both the queries.


1 Answers

UNION removes duplicate values. You probably want UNION ALL instead.

like image 84
Joe Stefanelli Avatar answered Nov 09 '22 02:11

Joe Stefanelli