Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding DISTINCT to a UNION query

How do I get distinct title.id's from this:

 SELECT Title.id, Title.title FROM titles as Title HAVING points > 0 
 UNION ALL 
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1

There is more to the query but this should be enough to go on.

like image 684
cdub Avatar asked Dec 03 '22 08:12

cdub


2 Answers

Just remove the ALL. Some flavors allow adding DISTINCT instead of ALL to be more explicit, but that's redundant having that the default is always to filter our duplicates.

MySQL - http://dev.mysql.com/doc/refman/5.0/en/union.html
MSSQL - http://msdn.microsoft.com/en-us/library/ms180026.aspx
ORACLE - https://docs.oracle.com/cd/B28359_01/server.111/b28286/queries004.htm
PostgreSQL - http://www.postgresql.org/docs/8.3/interactive/queries-union.html
etc.

like image 68
Alin Purcaru Avatar answered Dec 05 '22 22:12

Alin Purcaru


Isn't the simple way just get rid of the union and the second part altogether:

SELECT Title.id, Title.title FROM titles as Title HAVING points > 0 

since HAVING points > 0 includes anything with HAVING points > 1?

like image 42
Bohemian Avatar answered Dec 05 '22 22:12

Bohemian