[英]SQL multiple left join as new columns performance
I have 3 tables:我有 3 张桌子:
account帐户
id ID | name姓名 |
---|---|
1 1 | Google谷歌 |
2 2 | Apple苹果 |
custom_field自定义字段
id ID | name姓名 |
---|---|
1 1 | Phone电话 |
2 2 | Email Email |
custom_field_submission custom_field_submission
id ID | custom_field_id custom_field_id | entity_id entity_id | value价值 |
---|---|---|---|
1 1 | 1 1 | 1 1 | 555-444-333 555-444-333 |
2 2 | 1 1 | 2 2 | 111-111-111 111-111-111 |
3 3 | 2 2 | 1 1 | google@goog.com google@goog.com |
4 4 | 2 2 | 2 2 | apple@apple.com苹果@apple.com |
Expected result after query查询后的预期结果
id ID | name姓名 | Phone电话 | Email Email |
---|---|---|---|
1 1 | Google谷歌 | 555-444-333 555-444-333 | google@goog.com google@goog.com |
2 2 | Apple苹果 | 111-111-111 111-111-111 | apple@apple.com苹果@apple.com |
I have a query like this:我有一个这样的查询:
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
In the reality I have 20 custom fields for 10 000 accounts.实际上,我为 10 000 个帐户提供了 20 个自定义字段。 Where I run the query It is very slow (3-4 seconds)我在哪里运行查询非常慢(3-4秒)
Do you have an idea to manage optimize this?你有一个想法来管理优化这个吗?
Thanks.谢谢。
What you need here is a pivot query:您需要的是 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.