簡體   English   中英

SQL 多個左連接作為新列性能

[英]SQL multiple left join as new columns performance

我有 3 張桌子:

帳戶

ID 姓名
1 谷歌
2 蘋果

自定義字段

ID 姓名
1 電話
2 Email

custom_field_submission

ID custom_field_id entity_id 價值
1 1 1 555-444-333
2 1 2 111-111-111
3 2 1 google@goog.com
4 2 2 蘋果@apple.com

查詢后的預期結果

ID 姓名 電話 Email
1 谷歌 555-444-333 google@goog.com
2 蘋果 111-111-111 蘋果@apple.com

我有一個這樣的查詢:

SELECT
a.id,
a.name,
phone.value as phone,
email.value as email

FROM account a

LEFT JOIN ( 
  SELECT DISTINCT custom_field_submission.value, custom_field_submission.entity_id
  FROM custom_field_submission
  WHERE custom_field_submission.custom_field_id = 1) AS phone 
ON phone.entity_id = a.id

LEFT JOIN ( 
  SELECT DISTINCT custom_field_submission.value, custom_field_submission.entity_id
  FROM custom_field_submission
  WHERE custom_field_submission.custom_field_id = 2) AS email 
ON email.entity_id = a.id

實際上,我為 10 000 個帳戶提供了 20 個自定義字段。 我在哪里運行查詢非常慢(3-4秒)

你有一個想法來管理優化這個嗎?

謝謝。

您需要的是 pivot 查詢:

SELECT
    a.id,
    a.name,
    MAX(CASE WHEN cf.name = 'Phone' THEN cfs.value END) AS Phone,
    MAX(CASE WHEN cf.name = 'Email' THEN cfs.value END) AS Email
FROM account a
LEFT JOIN custom_field_submission cfs
    ON cfs.entity_id = a.id
LEFT JOIN custom_field cf
    ON cf.id = cfs.custom_field_id
GROUP BY
    a.id,
    a.name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM