这可能是一个基本的SQL问题,但我很想知道答案。
我需要从数据库中获取前一条记录。哪个查询效率更高,哪个查询使用where子句或按顺序排序?
示例:
表
Movie
id name isPlaying endDate isDeleted
以上是用于存储电影记录的版本化表格。
如果endDate不为null且isDeleted = 1,则记录为旧,并且此表中已存在更新的记录。
因此,要获取当前正在播放的电影“角斗士”,我可以用两种方式编写查询:
1.
Select m.isPlaying
From Movie m
where m.name=:name (given)
and m.endDate is null and m.isDeleted=0
2. Select TOP 1 m.isPlaying
From Movie m
where m.name=:name (given)
order by m.id desc --- This will always give me the active record (one which is not deleted)
哪种查询更快且正确的方法呢?
更新: id是唯一的索引列,id是唯一键。我期待查询只返回一个结果。
更新
示例:
Movie
id name isPlaying EndDate isDeleted
3 Gladiator 1 03/1/2017 1
4 Gladiator 1 03/1/2017 1
5 Gladiator 0 null 0
答案 0 :(得分:0)
我会使用where
子句:
Select m.isPlaying
From Movie m
where m.id = :id and m.endDate is null and m.isDeleted = 0;
这可以利用(id, isDeleted, endDate)
上的索引。
另外,两者并不相同。当第一个返回1时,第二个可能返回多行。或者当第一个返回none时,第二个可能返回一行。
答案 1 :(得分:0)
第一个选项可能会返回超过1行。也许你知道它不会因为你知道你存储的数据但SQL引擎没有,这会影响它的执行计划。
考虑到ID
列上只有1个索引,第二个查询应该理论上更快,因为它会从中进行索引扫描最高ID
,其中包含给定name
的谓词,在第一场比赛时停止。
第一个查询会在比较列name
,endDate
和isDeleted
时进行全表扫描,因为它不会在匹配的第一个结果处停止。
为两个查询发布执行计划可能会启发一些松散的电缆。