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-11-04部署MySQL集群项目实战:新手入门教程
- 2024-11-04如何部署MySQL集群资料:新手入门指南
- 2024-11-02MySQL集群项目实战:新手入门指南
- 2024-11-02初学者指南:部署MySQL集群资料
- 2024-11-01部署MySQL集群教程:新手入门指南
- 2024-11-01如何部署MySQL集群:新手入门教程
- 2024-11-01部署MySQL集群学习:新手入门教程
- 2024-11-01部署MySQL集群入门:新手必读指南
- 2024-10-23BinLog入门:新手必读的MySQL二进制日志指南
- 2024-10-23Binlog入门:MySQL数据库的日志管理指南