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

2021/7/21 19:21:11

本文主要是介绍mysql中 or和and一起用时,发生的现象,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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' ) )


这篇关于mysql中 or和and一起用时,发生的现象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程