在mysql查询中使用if语句

时间:2016-01-18 09:00:52

标签: mysql sql

我想在sql查询中使用if语句:

我想要的是什么:

if(tractions_delivery.send_date_id !=0 ){

           date_send_commodities.id  = tractions_delivery.send_date_id
}

我的疑问:

        from

            tractions_delivery,user_address,province,city,date_send_commodities,users

        WHERE

        tractions_delivery.tr_id = $tr_id
        AND
        tractions_delivery.address_id = user_address.id
        AND
        user_address.province_id = province.id
        AND
        user_address.city_id      = city.id
        AND
        //not work
        (tractions_delivery.send_date_id IS NOT 0 date_send_commodities.id  = tractions_delivery.send_date_id)

        AND
        users.id = user_address.user_id

3 个答案:

答案 0 :(得分:1)

您只能在存储过程或函数中使用if语句。如果你只是编写一个sql语句,那么你不能在查询周围使用if语句。但您可以在查询中使用逻辑,例如:

SELECT CASE WHEN col1 = col2 THEN'col1 equals col2' else 'col1 doesnt equal col2' ELSE
FROM table1

所以周围不起作用,但在字段列表中,您可以创建CASE WHEN ELSE END逻辑。

答案 1 :(得分:1)

CASEIF()运营商可以提供帮助。

实施例中,

SELECT (CASE 1 WHEN 1 THEN 'One' WHEN 2 THEN 'Two' ELSE 'More' END) 'Result';

OR

SELECT IF(1=1, 'One', 'Two') 'Result';

可以在CASE子句中使用这些IF()SELECT运算符来有条件地解释列值并返回结果集。

注意:请勿将CASE运算符与' CASE条件句法块'混淆。以END CASE结尾。

答案 2 :(得分:1)

您可以使用CASE语句

SELECT 
*
FROM
 tractions_delivery,
 user_address,
 province,
 city,
 date_send_commodities,users
WHERE
 tractions_delivery.tr_id = $tr_id AND
 tractions_delivery.address_id = user_address.id AND
 user_address.province_id = province.id AND
 user_address.city_id = city.id AND
 CASE WHEN tractions_delivery.send_date_id != 0 THEN date_send_commodities.id = tractions_delivery.send_date_id ELSE 1=1 END AND
 users.id = user_address.user_id