同一条sql语句,只是将条件换了一下位置,为何查询的结果不同?
rt.
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where m.discBarcode is not null and b.MetaDataContent like '%赵薇%' or b.MetaDataContent like '%陈可辛%' or b.MetaDataContent like '%1%' and b.metaDataID = '102' --(5 行受影响)查询出5条数据
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where m.discBarcode is not null and b.MetaDataContent like '%赵薇%' or b.MetaDataContent like '%1%' or b.MetaDataContent like '%陈可辛%' and b.metaDataID = '102' --(13 行受影响)查询出13条数据
请问这是什么情况?
[解决办法]
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where m.discBarcode is not null and b.MetaDataContent like '%赵薇%' or b.MetaDataContent like '%陈可辛%' or b.MetaDataContent like '%1%' and b.metaDataID = '102'第一句实际上是:
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where (m.discBarcode is not null and b.MetaDataContent like '%赵薇%' )or b.MetaDataContent like '%陈可辛%' or (b.MetaDataContent like '%1%' and b.metaDataID = '102')注意括号,第二句实际上是:
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where (m.discBarcode is not null and b.MetaDataContent like '%赵薇%' )or b.MetaDataContent like '%1%' or (b.MetaDataContent like '%陈可辛%' and b.metaDataID = '102' )这是优先级的问题
[解决办法]
这主要是因为and和or的优先级不一样,and的优先级高于or的优先级:
第一个语句:
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where m.discBarcode is not null and b.MetaDataContent like '%赵薇%' or b.MetaDataContent like '%陈可辛%' or b.MetaDataContent like '%1%' and b.metaDataID = '102' --(5 行受影响)查询出5条数据
相当于,注意我的括号哈:
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where (m.discBarcode is not null and b.MetaDataContent like '%赵薇%') or b.MetaDataContent like '%陈可辛%' or (b.MetaDataContent like '%1%' and b.metaDataID = '102')
而第二个语句呢:
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where m.discBarcode is not null and b.MetaDataContent like '%赵薇%' or b.MetaDataContent like '%1%' or b.MetaDataContent like '%陈可辛%' and b.metaDataID = '102' --(13 行受影响)
相当于:
select distinct m.* from mediaPack m left join MetaDataRecord b on m.id = b.MediaPackID where (m.discBarcode is not null and b.MetaDataContent like '%赵薇%') or b.MetaDataContent like '%1%' or (b.MetaDataContent like '%陈可辛%' and b.metaDataID = '102')
所以相当于两条语句是不一样的,所以导致结果不同。
建议这种包含多个and和or的时候,通过括号把查询条件括起来