SQL 多个左连接作为新列的性能
SQL multiple left join as new columns performance
我有 3 张桌子:
账户
id
name
1
Google
2
Apple
custom_field
id
name
1
Phone
2
Email
custom_field_submission
id
custom_field_id
entity_id
value
1
1
1
555-444-333
2
1
2
111-111-111
3
2
1
google@goog.com
4
2
2
apple@apple.com
查询后的预期结果
id
name
Phone
Email
1
Google
555-444-333
google@goog.com
2
Apple
111-111-111
apple@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
实际上我有 10000 个帐户的 20 个自定义字段。我在哪里 运行 查询很慢(3-4 秒)
你有管理优化这个的想法吗?
谢谢。
这里你需要的是一个数据透视查询:
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;
我有 3 张桌子:
账户
id | name |
---|---|
1 | |
2 | Apple |
custom_field
id | name |
---|---|
1 | Phone |
2 |
custom_field_submission
id | custom_field_id | entity_id | value |
---|---|---|---|
1 | 1 | 1 | 555-444-333 |
2 | 1 | 2 | 111-111-111 |
3 | 2 | 1 | google@goog.com |
4 | 2 | 2 | apple@apple.com |
查询后的预期结果
id | name | Phone | |
---|---|---|---|
1 | 555-444-333 | google@goog.com | |
2 | Apple | 111-111-111 | apple@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
实际上我有 10000 个帐户的 20 个自定义字段。我在哪里 运行 查询很慢(3-4 秒)
你有管理优化这个的想法吗?
谢谢。
这里你需要的是一个数据透视查询:
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;