gpt4 book ai didi

mysql - 将 SQL 查询包装在括号中会导致语法错误

转载 作者:可可西里 更新时间:2023-11-01 08:31:20 33 4
gpt4 key购买 nike

以下查询有效:

SELECT DISTINCT `number`
FROM `employee`
WHERE `number` IN
(SELECT `department_manager`
FROM `department`)
UNION
(SELECT DISTINCT `manager`
FROM `employee`
WHERE `manager` IS NOT NULL)

但是一旦我用括号括起查询,它就不再起作用了:

 (SELECT DISTINCT `number`
FROM `employee`
WHERE `number` IN
(SELECT `department_manager`
FROM `department`)
UNION
(SELECT DISTINCT `manager`
FROM `employee`
WHERE `manager` IS NOT NULL))

导致语法错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION

将其他选择查询包裹在括号中不会导致问题,例如:

(SELECT DISTINCT number FROM johnson.employee);

这些有什么区别?

最佳答案

这与 MySQL 实现其 SQL 语法的方式有关。

A <query>可以是:

SELECT ... [ UNION <query>]

( SELECT ... ) [ UNION <query> ]

但显然不是

( SELECT ... UNION <query> )

阅读sql/sql_yacc.yy如果您需要详细信息,请在 MySQL 源代码中查看。

作为解决方法,您可以这样做:

SELECT * FROM (SELECT ... UNION SELECT ... ) AS t;

关于mysql - 将 SQL 查询包装在括号中会导致语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26105253/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com