为什么UNION ALL有和没有括号表现有什么不同?(Why is UNION ALL with a

2019-09-26 14:32发布

I have this query implemented in two ways:

SELECT race1, mode1
FROM organization 
WHERE condition = 1 LIMIT 1

UNION ALL

(SELECT race2, mode2
FROM   organization 
WHERE  condition = 1 LIMIT 1)

UNION ALL

(SELECT race, mode FROM  organization_new
WHERE PK_Id = 1)

And

SELECT race1, mode1
FROM organization 
WHERE condition = 1 LIMIT 1

UNION ALL

SELECT race2, mode2
FROM   organization 
WHERE  condition = 1 LIMIT 1

UNION ALL

SELECT race, mode FROM  organization_new
WHERE PK_Id = 1

As you can see, the difference is only in the parentheses in the first query. In the first query, I get the results as expected (gets all the values from all three selects, no explanation needed). But when I go ahead with the second query, I get results as desired but not as expected, that is only the values from first select which meets the WHERE clause. That is if there is a race1, mode1 where condition = 1, then I get only that result. If there isn't then I am getting race2, mode2 where condition = 1. If even the second select statement is empty, then I get the values according to third select statement. Why is UNION ALL behaving like an OR if no parentheses are provided?

Edit: I am using MySQL 5.0.51a

Answer 1:

那是因为你正在使用的限制。

MySQL参考说,如果你想使用ORDER BY或限制对个人选择,那么你必须用括号包围你的选择。

实施例(从MySQL参考):

通过或LIMIT应用于为了将个人选择,将围绕该SELECT括号内的条款:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

资源可以在这里找到: http://dev.mysql.com/doc/refman/5.0/en/union.html

编辑:更改后的参考链接,因为前一个是5.5的版本。 但回答didn`t变化。



文章来源: Why is UNION ALL with and without parenthesis behaving different?