主键思维定势导致的惨案
记录一下前段时间工作中遇到的问题,希望这血淋淋的惨案可以警醒与我有相同思维定势的网友。
众所周知一般情况下数据库中的记录是按照主键(主键是整数)递减排列的
select * from
Person.Address
这种情况下我们直接使用top (100),自然会正确的返回前100条记录
select top (100) * from Person.Address
所以,我就一直自认为下面的嵌套子查询会返回前100条记录
SELECT top (100) [AddressID]
,[AddressLine1]
,[AddressLine2]
,[City]
,[StateProvinceID]
,[PostalCode]
,[rowguid]
,[ModifiedDate]
FROM
[AdventureWorks].[Person].[Address]
where
stateprovinceid in
(
select StateProvinceID from Person.Address where
AddressID>10
)
就是这个思维定势导致的错误,令我郁闷了相当长的时间,一直以为是hibernate导致的错误,从没有想到是这个原因!
正确的写法如下
SELECT [AddressID]
,[AddressLine1]
,[AddressLine2]
,[City]
,[StateProvinceID]
,[PostalCode]
,[rowguid]
,[ModifiedDate]
FROM
[AdventureWorks].[Person].[Address]
where
AddressID in
(
select top(100) AddressID from Person.Address where
AddressID>10 order
by AddressID
)
SELECT top (100) [AddressID]
,[AddressLine1]
,[AddressLine2]
,[City]
,[StateProvinceID]
,[PostalCode]
,[rowguid]
,[ModifiedDate]
FROM
[AdventureWorks].[Person].[Address]
where
[AddressID] in
(
select [AddressID] from Person.Address where
AddressID>10
)
order by AddressID