mysql根据字段值动态查询多个表

问题:
a表得字段deviceType有1,2,3三个值,为1时查询b表,为2时查询c表,为3时查询d表:
将三个表关联起来再做判断:

 select a.*,
 (case when a.deviceType = 1 then b.name when a.deviceType = 2 then c.name else d.name end) as device_name,
 (case when a.device_type = 1 then b.number when a.device_type = 2 then c.number else d.number end) as device_number
 from a left join b on a.device_id = b.id
 left join c on a.device_id = c.id
 left join d on a.device_id = d.id

Mysql的三个条件判断:IF()、IFNULL()与CASE。
1.IF(expr,v1,v2)
若expr是TRUE(即:expr <> 0 and expr <> NULL),则该函数返回值为v1,否则返回值为v2

2.IFNULL(v1,v2)判断v1,v2是否为空
两个都不为空返回v1,
v1为空返回v2
v1不为空,v2为空返回v1

3.case
case expr when v1 then r1 when v2 then r2 else r3 end;
当expr满足v1就返回r1,若满足v2就返回r2,否则返回r3
case when expr then r1 when expr2 then r2 else r3 end
当expr为true就返回r1,当expr2为true就返回r2,否则就返回r3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值