mysql 多个and or_如何在mysql查询中使用一个或多个OR和AND

bd96500e110b49cbb3cd949968f18be7.png

I want to do a mysql query where data is retrieved from a database with some regulation.

I want to check which entries are similar to var1 or var2 or var3 and etc. AND are smaller than a given ID.

Like

SELECT *

FROM database

WHERE name = var1

OR name = var2

OR name = var3

AND id < 200

But the above line don't really works. Also when there is no more entry (which id is smaller than 200) it shows me however some entries.

Do you know what I mean? The query should select data which contains one of my wanted names AND which are smaller than an ID...

I have there a logic thinking problem...

解决方案

There is precedence with logical operators. When in doubt, use parenthesis.

In your case:

SELECT * FROM database WHERE (name = var1 OR name = var2 OR name = var3) AND id < 200

Your original query was interpreted as follows because the AND has higher precedence.

SELECT * FROM database WHERE name = var1 OR name = var2 OR (name = var3 AND id < 200)

Update

As commented by Rocket, you could condense your OR statements to IN since they operate on the same field. Doing so would remove the need for parentheses.

SELECT * FROM database WHERE name IN (var1,var2,var3) AND id < 200

Nonetheless, understanding the difference between the two original queries is important as you inevitably will write queries with multiple conditions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值