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

时间:2014-09-29 17:08:40

标签: mysql

以下查询有效:

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);

这些之间有什么区别?

2 个答案:

答案 0 :(得分:2)

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

<query>可以是:

SELECT ... [ UNION <query>]

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

但显然不是

( SELECT ... UNION <query> )

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

作为解决方法,您可以执行此操作:

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

答案 1 :(得分:0)

查询周围的括号是子查询 - 认为这几乎就像一个子程序,首先执行内部查询,然后在外部查询的上下文中计算其结果。在第二个示例中,您定义的子查询不存在外部查询,因此出现语法错误。

您可以将第二个示例转换为有效的sql,只需在第一个括号前加SELECT,在右括号后加“FROM DUMMY”;试试吧。