mysql中 or和and一起用时,发生的现象
2021/7/21 19:21:11
本文主要是介绍mysql中 or和and一起用时,发生的现象,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
mysql中 or和and一起用时,发生的现象
1.or
的使用,以下的查询结果为 :feeitemNo
为11
或者为22
的数据
SELECT a.* FROM BSPPurchaseApplyBill a where a.feeItemNo = '11' or a.feeItemNo='22'
2.and
的使用:以下的查询结果为:feeitemNo
为11
和id
为22
的数据
SELECT a.* FROM BSPPurchaseApplyBill a where a.feeItemNo = '11' and a.id='22'
3.容易错误的现象为
SELECT bb.feeItemNo, a.*, bb.isNewOrOld AS isNewOrOld, '' AS kuState, ln.unitNm AS unitNm FROM VMIStorageOutBill a INNER JOIN VMIStorageOutBillDetail b ON a.storageOutBillNo = b.storageOutBillNo LEFT JOIN LSpareMateriel g ON b.materielNo = g.materielNo LEFT JOIN Lunit ln ON g.unitId = ln.id INNER JOIN BSPPurchaseApplyBill bb ON a.purchaseApplyBIlNo= bb.purchaseApplyBIlNo INNER JOIN VMIStorageAddBillDetail f ON a.purchaseApplyBIlNo = f.purchaseApplyBillNo where 1=1 and f.storageInfoId is not null and f.storageInfoId >0 and b.trueAmount<> b.planAmount and a.isrtDt >= '2021-02-01' and a.state !='已出库' and bb.feeItemNo = '01411100' or bb.feeItemNo in (SELECT agent_no from vmi_role_agent where user_id = 838358 and is_del=1 )
我们的本意是要查询feeitemNo
为 01411100
或者为某列表中的数据,但是查询出的结果却比我们预想的要多的多,是为什么呢? 因为这种查询,数据库识别的是从where
到第一个feeitemNo
为一个条件,在or
后面的in
为一个条件,因此在后面的or
中并没有自动加上前面的and f.storageInfoId is not null and f.storageInfoId >0 and b.trueAmount<>b.planAmount and a.isrtDt >= '2021-02-01' and a.state !='已出库'
,如果要手动加上,那么我们的sql会变的十分繁琐。
and bb.feeItemNo = '01411100' or bb.feeItemNo in (SELECT agent_no from vmi_role_agent where user_id = 838358 and is_del=1 )
正确写法
将or
用括号括起来,这样就会达到预想的效果,注意:and
要写在括号外面!!!
SELECT bb.feeItemNo, a.*, bb.isNewOrOld AS isNewOrOld, '' AS kuState, ln.unitNm AS unitNm FROM VMIStorageOutBill a INNER JOIN VMIStorageOutBillDetail b ON a.storageOutBillNo = b.storageOutBillNo LEFT JOIN LSpareMateriel g ON b.materielNo = g.materielNo LEFT JOIN Lunit ln ON g.unitId = ln.id INNER JOIN BSPPurchaseApplyBill bb ON a.purchaseApplyBIlNo= bb.purchaseApplyBIlNo INNER JOIN VMIStorageAddBillDetail f ON a.purchaseApplyBIlNo = f.purchaseApplyBillNo WHERE 1 = 1 AND f.storageInfoId IS NOT NULL AND f.storageInfoId > 0 AND b.trueAmount <> b.planAmount AND a.isrtDt >= '2021-02-01' AND a.state != '已出库' AND ( bb.feeItemNo = '00960168' OR bb.feeItemNo IN ( '01411100' ) )
这篇关于mysql中 or和and一起用时,发生的现象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-26MySQL查出时间比实际晚8小时的解决方案
- 2024-04-01JPA不识别MySQL的枚举类型
- 2024-03-30mysql数据库表卡死解决方法
- 2024-03-15MySQL多数据源笔记5-ShardingJDBC实战
- 2024-03-11natural join mysql
- 2024-03-11关于VS2017,VS2015 中利用 EF使用Mysql 不显示数据源问题解决方案
- 2024-02-26mysql 阿里云xb后缀备份文件恢复-icode9专业技术文章分享
- 2024-02-22docker mysql 5.7
- 2024-02-18从 20 多套 MySQL 到 1 套 TiDB丨骏伯网络综合运营管理平台应用实践
- 2024-02-07mysql 外键索引入门介绍,为什么工作中很少有人使用?