编写此查询的正确方法是什么?

时间:2013-10-03 02:11:15

标签: sql sql-server sql-server-2008

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

代码:

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.

如何更正此选择查询?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

稍微扩展别人所说的话......

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

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

这就是订购subquery没有任何意义的原因 - 只有顶级订单会“坚持”以对客户产生任何影响。