mysql查询语句where后面加if判断
格式:IF(<condition>,<value if true>,<value if false>)
释义:如果condition为true,则执行前面的条件;condition为false,则执行后面的条件
示例:
查找名字为张三并且是地区是湖南,和名字不是张三的所有用户:
SELECT * FROM USER WHERE IF( NAME ='张三',address LIKE '%湖南%',1=1 )
简单的写法:
SELECT * FROM USER WHERE 1 = 1 AND NAME != '张三' OR (NAME = '张三' AND address LIKE '%湖南%' )
也可以这么写:
SELECT * FROM USER WHERE 1 = 1 AND NAME != '张三' OR address LIKE '%湖南%'
项目代码:
查询s3为null的全部记录和s3不为null,而且p.display_code 在s3里面的记录
WHERE 1 = 1 AND s1 = '5' AND IF( s3 IS NULL,TRUE,FIND_IN_SET(p.display_code, s3))
mysql查询语句where后面加if判断
说明:WHERE IF(条件, true执行条件, false执行条件 )
SELECT * FROM book WHERE IF(price > 120, btypeid=10, btypeid=11);
以上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 union select * from book where price < 120 and btypeid = 11;
准确的来说是select * from book where price > 120 and btypeid =10 union select * from book where price <=120 and btypeid = 11;
以下sql语句同理,只不过是多了一个limit 0,1;取前面1条记录。
SELECT * FROM book WHERE IF(price > 120, btypeid=10, btypeid=11) limit 0,1;