让我们说我有一些实体,这些实体的名称在表name
中,键为name_id
。在同一表中,这些名称可以具有“替代形式”,并带有外键primary_name_id
。关键是,实体仅引用了主要名称。因此,如果我想要某些实体的主要名称和替代名称,可以这样做:
SELECT e.entity_id, n.name_id
FROM entity e
JOIN entity_to_name e2n ON e2n.entity_id = e.entity_id
JOIN name n ON e2n.name_id = n.name_id
UNION
SELECT e.entity_id, na.name_id
FROM entity e
JOIN entity_to_name e2n ON e2n.entity_id = e.entity_id
JOIN name n ON e2n.name_id = n.name_id
JOIN name na ON na.primary_name_id = n.name_id
编辑:表格和所需结果的示例:
-------------------
entity_id | name_id
-------------------
entity1 | n1
entity2 | n2
entity3 | n3
-------------------
-----------------------------------
name_id | primary_name_id | name
-----------------------------------
n1 | NULL | Entity 1
n2 | NULL | Entity 2
n3 | NULL | Entity 3
n4 | n1 | Entity Uno
n5 | n2 | Entity Duo
n6 | n2 | Entity Zwei
------------------------------------
And as a result I want
---------------------
entity_id | name_id
---------------------
entity1 | n1
entity1 | n4
entity2 | n2
entity2 | n5
entity2 | n6
entity3 | n3
但是实际上,名称的JOIN路径更为复杂,我希望避免重复两次。有一种方法可以在一个查询中执行此操作吗?
答案 0 :(得分:2)
以下查询应为您提供预期的答案:
SELECT n.name_id
, e.entity_Id
FROM name n
LEFT JOIN entity e
ON coalesce(n.primary_name_id, n.name_id) = e.name_id