如何避免多个子查询作为表达式(SQL优化)

时间:2017-11-03 09:27:31

标签: sql postgresql pivot crosstab

我有两张桌子 表A

user_id             external_party_id
  1                        6

表B

user_id    activated    user_mode         sale_mode
  1          false      'Customer'         'Web'          
  1          true       'Customer'         'Local'        
  1          true       'Partner'          'Web'         
  1          true       'Partner'          'Local'           

RESULT

user_id   external_party_id   customer_web   customer_local  partner_web   partner_local
  1         6                   false          true        true             true
  2         7                   false          false        true             false

现在我有以下类型的查询

SELECT
  u.*,
  (SELECT activated
   FROM TABLE_B
   WHERE user_id = u.user_id AND user_mode = 'Customer' AND sale_mode = 'Web'
  ) AS customer_web,
  (SELECT activated
   FROM TABLE_B
   WHERE user_id = u.user_id AND user_mode = 'Customer' AND sale_mode = 'Local'
  ) AS customer_local,
  (SELECT activated
   FROM TABLE_B
   WHERE user_id = u.user_id AND user_mode = 'Partner' AND sale_mode = 'Web'
  ) AS partner_web,
  (SELECT activated
   FROM TABLE_B
   WHERE user_id = u.user_id AND user_mode = 'Partner' AND sale_mode = 'Local'
  ) AS partner_local,
FROM TABLE_A AS u;

我想知道是否有更好的方法来实现这一目标。此查询是否尝试四次查询TABLE_B以填充每个列值?

2 个答案:

答案 0 :(得分:0)

使用条件聚合

SELECT
  u.user_id,u.external_party_id,
  MAX (CASE WHEN user_mode = 'Customer' AND sale_mode = 'Web' THEN activated END) AS customer_web,
  MAX (CASE WHEN user_mode = 'Customer' AND sale_mode = 'Local' THEN activated END) AS customer_local,
  MAX (CASE WHEN user_mode = 'Partner' AND sale_mode = 'Web' THEN activated END) AS partner_web,
  MAX (CASE WHEN user_mode = 'Partner' AND sale_mode = 'Local' THEN activated END) AS partner_local
FROM TABLE_A AS u
LEFT JOIN TABLE_B b ON b.user_id = u.user_id
GROUP BY u.user_id,u.external_party_id

答案 1 :(得分:0)

格式不完全相同,但您可以使用直接左连接重新表示:

SELECT
    a.*,
    b.activated,
    b.user_mode,
    b.sales_mode
FROM TABLE_A AS a
LEFT JOIN TABLE_B AS b
    ON a.user_id = b.user_id AND
       user_mode IN ('Customer', 'Partner') AND
       sale_mode IN ('Web', 'Local');