mysql where后面if_mysql查询语句where后面加if判断

mysql查询语句where后面加if判断

f117161d257f4d277cbd4406c640fc2d.png

说明:WHERE  IF(条件,  true执行条件, false执行条件 )

SELECT * FROM book WHERE IF(price > 120, btypeid=10, btypeid=11);

167f982135fe193e672d44b5bc4d714c.png

以上sql查询语句,意思是查price字段大于120,当price大于120为真时,再找btypeid等于10的行记录,

当price大于120为假时,再找btypeid等于11的行记录。什么意思呢?咱们换句话说吧!

意思就是当price大于120为真时,执行语句为where price>120 and btypeid=10;

当price大于120为假时,执行语句为where price<120 and btypeid=11;准确来说应该是where price<=120 and btypeid=11;

其实说白了,SELECT * FROM  book WHERE IF(price > 120,  btypeid=10,  btypeid=11);这条sql语句等价于如下sql语句

select * from book where price > 120 and btypeid =10 unionselect * from book where price < 120 and btypeid = 11;

b6721cff26a0fbe5c469b0fbea23f7c9.png

准确的来说是select * from book where price > 120 and btypeid =10 unionselect * from book where price <=120 and btypeid = 11;

cf11bee620ef72b1d1d9442f86bb141f.png

以下sql语句同理,只不过是多了一个limit 0,1;取前面1条记录。

SELECT * FROM book WHERE IF(price > 120, btypeid=10, btypeid=11) limit 0,1;

8adba98c3c35776acd5f720c0f2fd3ba.png

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值