需要帮助将子查询转换为JOIN

时间:2014-01-17 02:12:48

标签: mysql sql join subquery

任何人都可以帮助我将这个基于子查询的查询转换为JOIN吗?

SELECT DISTINCT brm_products_assets_id,
(select brm_products_assets_value from brm_products_assets_values where brm_products_assets_id=a.brm_products_assets_id and brm_products_assets_def_id=1) as prod_asset_name,
(select brm_products_assets_value from brm_products_assets_values where brm_products_assets_id=a.brm_products_assets_id and brm_products_assets_def_id=3) as prod_asset_desc,
(select brm_products_assets_value from brm_products_assets_values where brm_products_assets_id=a.brm_products_assets_id and brm_products_assets_def_id=2) as prod_asset_type,
ifnull((select brm_products_assets_value from brm_products_assets_values where brm_products_assets_id=a.brm_products_assets_id and brm_products_assets_def_id=5),'') as file_order 
from brm_products_assets a where last_mnt_option!='d';

此查询目前需要20秒才能执行。我在brm_products_assets_value上尝试了一个索引,但它没有帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

您想要进行条件聚合,而不是单独的查询:

SELECT brm_products_assets_id,
       max(case when brm_products_assets_def_id = 1 then brm_products_assets_value
           end) as prod_asset_name,
       max(case when brm_products_assets_def_id = 2 then brm_products_assets_value
           end) as prod_asset_desc,
       max(case when brm_products_assets_def_id = 3 then brm_products_assets_value
           end) as prod_asset_type,
       max(case when brm_products_assets_def_id = 5 then brm_products_assets_value else ''
           end) as file_order
from brm_products_assets a join
     brm_products_assets_values b
     on b.brm_products_assets_id = a.brm_products_assets_id
where last_mnt_option <> 'd'
group by a.brm_products_assets_id;