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' ) )
标签:JOIN,bb,ln,用时,现象,feeItemNo,mysql,where,SELECT 来源: https://blog.csdn.net/Shengzhiying/article/details/118961037