mysql多表关联,根据第一个表中某一个字段的值不同,选择关联不同的表 。解决方案
作者:互联网
现有需求:mysql查询特定字段,根据第一个表中某一个字段的值不同,获取不同的表的特定字段值。
发现两种解决方案,如有其他方法,欢迎留言补充,互相交流,共同进步~~
解决方案:
方案一:
$sql1 = "SELECT t1.id,t1.name,t1.add_time,t1.is_adopt, CASE WHEN t1.customer_type=2 THEN (SELECT name FROM company_info as t2 WHERE t2.company_id=t1.customer_id) WHEN t1.customer_type=3 THEN (SELECT name FROM factory_info as t2 WHERE t2.factory_id=t1.customer_id) END AS company_name, CASE WHEN t1.customer_type=2 THEN '经销商' WHEN t1.customer_type=3 THEN '厂商' END AS company_type FROM brand as t1 order by t1.add_time desc,t1.is_adopt asc;"; 方案二: $sql3 = "select d.id,d.name,d.add_time,d.is_adopt, (case when d.customer_type = 2 then a.name when d.customer_type = 3 then b.name end) AS company_name, (CASE WHEN d.customer_type = 2 THEN '经销商' WHEN d.customer_type = 3 THEN '厂商' END) AS customer_type from brand as d left join company_info as a on a.company_id=d.customer_id left join factory_info as b on b.factory_id=d.customer_id order by d.add_time desc,d.is_adopt asc;"; 总结一下,一种是在查询字段时直接设置子查询;另一种是先设置字段,在后面通过左连接的形式关联表去查询。 两种方法均可实现。标签:customer,多表,name,company,t1,mysql,关联,type,id 来源: https://www.cnblogs.com/xccode/p/16055783.html