当我对我的数据库执行此查询时:
代码:
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.
如何更正此选择查询?
答案 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
没有任何意义的原因 - 只有顶级订单会“坚持”以对客户产生任何影响。