将DISTINCT添加到UNION查询

时间:2011-06-02 08:12:34

标签: mysql sql union distinct union-all

如何从中得到明确的title.id:

 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

查询还有更多内容,但这应该足够了。

3 个答案:

答案 0 :(得分:15)

只需删除ALL即可。有些风格允许添加DISTINCT而不是ALL更明确,但这是多余的,因为默认值总是过滤我们的重复项。

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

答案 1 :(得分:1)

不是简单的方法就是完全摆脱联盟和第二部分:

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

因为HAVING points > 0包含HAVING points > 1的任何内容?

答案 2 :(得分:0)

你可以像其他人建议的那样放弃ALL

如果两个查询使用相同的表并且仅在WHERE子句中或仅在HAVING子句中有所不同,那么您也可以使用它:

SELECT Title.id, Title.title FROM titles as Title
WHERE (1st query conditions)
   OR (2nd query conditions)

SELECT Title.id, Title.title FROM titles as Title
HAVING (1st query conditions)
    OR (2nd query conditions)