ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

mysql中 or和and一起用时,发生的现象

2021-07-21 10:58:51  阅读:201  来源: 互联网

标签:JOIN bb ln 用时 现象 feeItemNo mysql where SELECT


mysql中 or和and一起用时,发生的现象

1.or的使用,以下的查询结果为 :feeitemNo11或者为22的数据

SELECT a.* FROM BSPPurchaseApplyBill a
where a.feeItemNo = '11' or a.feeItemNo='22'

2.and的使用:以下的查询结果为:feeitemNo11id22的数据

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 )

我们的本意是要查询feeitemNo01411100或者为某列表中的数据,但是查询出的结果却比我们预想的要多的多,是为什么呢? 因为这种查询,数据库识别的是从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' ) )

标签:JOIN,bb,ln,用时,现象,feeItemNo,mysql,where,SELECT
来源: https://blog.csdn.net/Shengzhiying/article/details/118961037

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有