根据列值加入类型

时间:2015-12-11 13:40:59

标签: mysql sql query-optimization

我有两张桌子:

shops
id | shop_name | shop_type

products
id | shop_id | product_name

我需要LEFT JOIN products ON products.shop_id = shops.id IF shop_type is 0 我需要JOIN products ON products.shop_id = shops.id IF shop_type is 1。 什么是最快的解决方案?如果代码非常脏则无关紧要,性能是最重要的......

1 个答案:

答案 0 :(得分:1)

select *
from shops LEFT JOIN products ON products.shop_id = shops.id
where shop_type = 0 or (products.shop_id is not NULL and shop_type = 1)