MySQL IF声明?

时间:2012-02-24 18:29:18

标签: php mysql

我有一个巨大的SQL查询,我选择并格式化一堆行以导出到Excel。我想添加一个角色,几乎如果摆脱(角色ID)EXISTS和IS 3然后将其设置为角色1,否则将其设置为角色2。

当前的Mysql查询

SELECT uc_orders.billing_first_name AS 'First Name', uc_orders.billing_last_name AS 'Last 
Name', users.name AS 'Username', uc_orders.billing_street1 AS 'Address', 
uc_orders.billing_city AS 'City', uc_zones.zone_name AS 'State',uc_orders.billing_postal_code
 AS 'Postal Code', ROUND(uc_orders.order_total,2) AS 'Order Total'  FROM uc_orders, users,
 uc_zones WHERE uc_orders.uid!='0' AND uc_orders.uid = users.uid AND uc_orders.billing_zone =
 uc_zones.zone_id AND uc_orders.modified BETWEEN '1271124575' AND '1274978899'

但是用户不会总是存在于users_role数据库中(只有当它是3或其他某个数字时才存在,通常它不存在)。因此,如果它不存在,它也将返回“角色2”;

所以

  IF users.uid EXISTS IN users_role.uid THEN
    IF users_role.uid EQUALS users.uid AND users_role.rid = 3
      THEN
        return 'Role 1'
      ELSE
        return 'Role 2';
  ELSE return 'Role 2';

我如何在MySQL中执行此操作?或者PHP是唯一的方法吗?

3 个答案:

答案 0 :(得分:4)

您应该使用JOIN进行多表查询。还可以考虑格式化查询并使用别名以便于阅读。

SELECT
    `a`.`billing_first_name` as `First Name`,
    `a`.`billing_last_name` as `Last Name`,
    `b`.`name` as `Username`,
    `a`.`billing_street1` as `Address`,
    `a`.`billing_city` as `City`,
    `c`.`zone_name` as `State`,
    `a`.`billing_postal_code` as `Postal Code`,
    ROUND(`a`.`order_total`,2) as `Order Total`,
    IF(`d`.`rid` IS NOT NULL AND `d`.`rid`=3,'Role 1','Role 2') as `Role`
FROM `us_orders` as `a`
JOIN `users` as `b` ON `a`.`uid`=`b`.`uid`
JOIN `uc_zones` as `c` ON `a`.`billing_zone`=`c`.`zone_id`
LEFT JOIN `users_role` as `d` on `a`.`uid`=`d`.`uid`
WHERE `a`.`modified` BETWEEN '1271124575' AND '1274978899'

回答实际问题的部分是IF的行和LEFT JOIN的行。

答案 1 :(得分:1)

使用CASE语句。 CASE(rid) WHEN 3 THEN 'Role 1' ELSE 'Role 2' END;

可以找到有关CASE声明的信息here

    -- Kolinks SQL using a CASE statement
    SELECT
        `a`.`billing_first_name` as `First Name`,
        `a`.`billing_last_name` as `Last Name`,
        `b`.`name` as `Username`,
        `a`.`billing_street1` as `Address`,
        `a`.`billing_city` as `City`,
        `c`.`zone_name` as `State`,
        `a`.`billing_postal_code` as `Postal Code`,
        ROUND(`a`.`order_total`,2) as `Order Total`,
        CASE (`d`.`rid`) WHEN 3 THEN 'Role 1' ELSE 'Role 2' END; as `Role`
    FROM `us_orders` as `a`
    JOIN `users` as `b` ON `a`.`uid`=`b`.`uid`
    JOIN `uc_zones` as `c` ON `a`.`billing_zone`=`c`.`zone_id`
    LEFT JOIN `users_role` as `d` on `a`.`uid`=`d`.`uid`
    WHERE `a`.`modified` BETWEEN '1271124575' AND '1274978899'

答案 2 :(得分:1)

是的,有IF声明。还有一个IF()函数。这是IF语句的MySQL参考页面:

http://dev.mysql.com/doc/refman/5.0/en/if-statement.html