SQL在组合的一对一表中选择all

时间:2015-08-11 12:28:16

标签: sql

我有三个SQL表。

Table a
a.id
a.name
a.type

Table b
b.id
b.name
b.type

Table c
c.id
c.parent_id (contains the id from either a.id or b.id)
  • 表a中的每条记录在表c中都有一对一的相应记录
  • 表b中的每条记录在表c
  • 中都有一对一的相应记录

问题:

I want to select all records from table C and get back:
c.id
the name of the parent (either a.name or b.name)
the type of the parent (either a.type or b.type)

有效方法的任何建议吗?

2 个答案:

答案 0 :(得分:2)

SELECT c.id, parent.name as parent_name, parent.[type] as parent_type
FROM tablec c
INNER JOIN tablea parent on parent.id = c.parent_id
UNION
SELECT c.id, parent.name as parent_name, parent.[type] as parent_type
FROM tablec c
INNER JOIN tableb parent on parent.id = c.parent_id

使用内部联接过滤掉没有匹配的行。

但我同意Jorge的评论。如果parent_id是对不同表中的列的引用但不能成为合法的外键,则它是一个不好的标志,因为它引用了多个列。

答案 1 :(得分:1)

select c.id,
a.name, a.type
from tablea a left join tableb b 
on a.id = b.id
left join tablec c
on a.id = c.parent_id or b.id = c.parent_id
union 
select c.id,
b.name, b.type
from tablea a left join tableb b 
on a.id = b.id
left join tablec c
on a.id = c.parent_id or b.id = c.parent_id

union是一种方法,因为它只为表a和b中的名称和类型列提供唯一值。