sql – 具有内部选择查询错误的Oracle选择查询

前端之家收集整理的这篇文章主要介绍了sql – 具有内部选择查询错误的Oracle选择查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我收到sql错误并尝试解决,任何指针都会有帮助,

//这会被执行

SELECT empid FROM employees WHERE deptid IN(10,20,30,40);

//这会被执行

SELECT deptid FROM department WHERE description LIKE '%application%' 
  ORDER BY createddate DESC

但以下查询抛出错误

SELECT empid  FROM employees WHERE deptid IN (SELECT deptid FROM department WHERE description LIKE '%application%' 
  ORDER BY createddate DESC);

错误
ORA-00907:缺少右括号
00907. 00000 – “缺少右括号”

更新:07/14:

使用@dasblinkenlight中的确切解决方案进行更新:

The problem is placing ORDER BY in the WHERE clause subquery. sql
Syntax does not allow you to order elements of the subquery in the
WHERE clause,because it does not change the result of the query
overall

本文很好地解释了许多概念 – http://oraclequirks.blogspot.com/2008/01/ora-00907-missing-right-parenthesis.html

“ORA-00907: missing right parenthesis Clearly when one gets a message
like this,the first reaction is probably to verify what parenthesis
has been left out,but unfortunately there are no missing parentheses
at all in this statement.

To cut it short,the untold Syntax quirk is summarized as follows:
don’t use ORDER BY inside an IN subquery.

Now,one may object that indeed it doesn’t make sense to use the ORDER
BY inside an IN clause,which is true,because Oracle doesn’t care
about the row order inside an IN clause:”

我尝试使用WHERE子句和’=’而不是’IN’的sql语句,它仍然抛出错误:’缺少右括号’.

结论1:

“不要在WHERE子句子查询中使用ORDER BY”
或者“where子句中的子查询不允许在Oracle中使用ORDER BY”

结论2

本案例研究还显示了我们应该选择JOIN而不是选择子查询的场景

解决方法

问题是将ORDER BY放在WHERE子句子查询中. sql语法不允许您在WHERE子句中对子查询的元素进行排序,因为它不会更改整个查询的结果.

您应该将其移出以修复语法:

SELECT empid  FROM employees WHERE deptid IN
    (
        SELECT deptid FROM department WHERE description LIKE '%application%'
    )
ORDER BY createddate DESC

createddate is not a column in employees table. It exists only in department table

然后,您需要加入department表,并在其中一个列上使用ORDER BY:

SELECT e.empid
FROM employees e
JOIN department d ON e.deptid = d.deptid
WHERE d.description LIKE '%application%'
ORDER BY d.createddate DESC
原文链接:/mssql/78505.html

猜你在找的MsSQL相关文章