mysql - 如何加入 table 中的动态列
mysql - how to join with dynamin column in table
我有三个 table,如下所示:
calls_list (table)
id
line
rel_type
rel_id
1
3
user
2
2
10
lead
1
用户(table)
id
name
phone
1
mehran
99999
2
reza
222222
领先(table)
id
title
status
1
lead_1
confirmed
2
lead_2
pending
我想在calls_listtable上说当select如果rel_type列等于lead值,加入leadtable
但是如果rel_type列等于用户值,加入用户table
我的查询是:
SELECT * FROM calls_list 作为调用
LEFT OUTER JOIN 用户作为用户 ON users.id = calls.rel_id
LEFT OUTER JOIN lead as lead ON lead.id = calls.rel_id
但不工作
这可能吗?你能帮帮我吗
您需要将每个连接限制为只有正确类型的连接:
SELECT *
FROM calls_list AS c
LEFT OUTER JOIN users AS u
ON u.id = c.rel_id AND c.rel_type = 'user'
LEFT OUTER JOIN lead AS l
ON l.id = c.rel_id AND c.rel_type = 'lead'
我有三个 table,如下所示:
calls_list (table)
id | line | rel_type | rel_id |
---|---|---|---|
1 | 3 | user | 2 |
2 | 10 | lead | 1 |
用户(table)
id | name | phone |
---|---|---|
1 | mehran | 99999 |
2 | reza | 222222 |
领先(table)
id | title | status |
---|---|---|
1 | lead_1 | confirmed |
2 | lead_2 | pending |
我想在calls_listtable上说当select如果rel_type列等于lead值,加入leadtable 但是如果rel_type列等于用户值,加入用户table
我的查询是:
SELECT * FROM calls_list 作为调用 LEFT OUTER JOIN 用户作为用户 ON users.id = calls.rel_id LEFT OUTER JOIN lead as lead ON lead.id = calls.rel_id
但不工作
这可能吗?你能帮帮我吗
您需要将每个连接限制为只有正确类型的连接:
SELECT *
FROM calls_list AS c
LEFT OUTER JOIN users AS u
ON u.id = c.rel_id AND c.rel_type = 'user'
LEFT OUTER JOIN lead AS l
ON l.id = c.rel_id AND c.rel_type = 'lead'