我有一个查询,我必须加入2表,如何简化以下查询
这是组织表结构
table : organizations
id name
1 A
2 B
3 C
4 D
这是org_mapping表结构
table : org_mapping mapping table structure
id org_id service_provider_id
1 1 2
2 4 1
SELECT om.service_provider_id AS associated_with,
o.name,
o.logo,
o.is_active AS active
FROM org_mapping om
LEFT JOIN organizations o
ON om.service_provider_id = o.id
WHERE org_id = ?
AND o.is_active = 1
UNION ALL
SELECT om.org_id AS associated_with,
o.name,
o.logo,
o.is_active AS active
FROM org_mapping om
LEFT JOIN organizations o
ON om.org_id = o.id
WHERE service_provider_id = ?
AND o.is_active = 1
有什么我可以在工会之外加入,
如果我给2,我希望输出为组织1和4
答案 0 :(得分:1)
这取决于您希望以另一种方式查看结果
Left Join
organizations
表两次获得结果,但数据将并排显示,UNION
将数据一个接一个地放置
SELECT om.service_provider_id AS associated_with,
o.name,
o1.name
FROM org_mapping om
LEFT JOIN organizations o
ON om.service_provider_id = o.id
LEFT JOIN organizations o1
ON om.org_id = o1.id