-1

当我对我的数据库执行此查询时:

代码:

SELECT TOP 20 
ha.datetime as ha_date, 
ha.id_hist_calls as ha_id_hist_calls, 
ha.name as ha_name, 
s.name as s_name, 
ss.name as ss_name 
FROM Hist_answer ha 
left join Hist_calls hc on hc.id_hist_calls = ha.id_hist_calls 
left join Service s on s.id_service = ha.from_id_service 
left join Service ss on ss.id_service = ha.id_service 

WHERE ha.id_hist_calls NOT IN ( 
SELECT 
ha.id_hist_calls as ha_id_hist_calls 
FROM Hist_answer ha 
WHERE ha.id_firm='39273' AND ha.datetime BETWEEN '2010.06.01 00:00:000' AND '2013.10.01 00:00:000' 
ORDER BY ha.datetime ASC 
) 

AND ha.id_firm='39273' 
AND ha.datetime BETWEEN '2010.06.01 00:00:000' AND '2013.10.01 00:00:000' 
ORDER BY ha.datetime ASC

我收到此错误:

Msg 1033, Level 15, State 1, Line 17
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

如何更正此选择查询?

4

2 回答 2

1

从子查询中删除 ORDER BY 子句

SELECT TOP 20 
ha.datetime as ha_date, 
ha.id_hist_calls as ha_id_hist_calls, 
ha.name as ha_name, 
s.name as s_name, 
ss.name as ss_name 
FROM Hist_answer ha 
left join Hist_calls hc on hc.id_hist_calls = ha.id_hist_calls 
left join Service s on s.id_service = ha.from_id_service 
left join Service ss on ss.id_service = ha.id_service 

WHERE ha.id_hist_calls NOT IN ( 
SELECT 
ha.id_hist_calls as ha_id_hist_calls 
FROM Hist_answer ha 
WHERE ha.id_firm='39273' AND ha.datetime BETWEEN '2010.06.01 00:00:000' AND '2013.10.01 00:00:000' 
) 

AND ha.id_firm='39273' 
AND ha.datetime BETWEEN '2010.06.01 00:00:000' AND '2013.10.01 00:00:000' 
ORDER BY ha.datetime ASC
于 2013-10-03T02:26:14.613 回答
1

为了扩展其他人所说的内容......

SQL 是基于集合的,集合基本上是无序的。

NOT IN subquery不关心顺序,subquery因为它是基于集合的操作。DBMS 可能会选择提供最佳性能的特定物理顺序,但从逻辑的角度来看,顺序并不重要。

这就是为什么订购没有任何目的subquery- 只有顶部的 ORDER BY 才会“坚持”以对客户产生任何影响。

于 2013-10-03T02:48:09.043 回答