我有一个巨大的sql查询,在这里我选择并格式化一堆行,以便导出到Excel。我想再添加一个角色,如果rid(role id)存在并且是3,那么将其设置为role 1,否则将其设置为role 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'
然而,用户并不总是存在于用户角色角色数据库中(只有当它是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是唯一的方法?
最佳答案
您应该使用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
的行。关于php - MySQL IF语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9436073/