在SQL中为缺少的属性收集实体属性值为null

时间:2013-08-24 09:48:56

标签: sql join

我在表中有一些实体,在另一个表中有属性和值。我想创建一个select,我可以在其中看到每个实体的特定属性值,如果缺少该属性,则返回null。如何使用标准SQL执行此操作?

这是设置:

create table person (id int not null, nick varchar(32) not null);

insert into person (id, nick) values (1, 'John');
insert into person (id, nick) values (2, 'Peter');

create table req_attributes (name varchar(32));

create table person_attributes (id int not null, 
                                person_id int not null,
                                attribute varchar(32) not null,
                                value varchar(64) not null);

insert into person_attributes values (1, 1, 'age', '21');
insert into person_attributes values (2, 1, 'hair', 'brown');
insert into person_attributes values (3, 2, 'age', '32');
insert into person_attributes values (4, 2, 'music', 'jazz');

这是我目前的选择陈述:

select * from person join person_attributes on 
  person.id = person_attributes.person_id
  where attribute = 'hair';

显然彼得不在结果集中,因为我们没有关于他头发的信息。我想让他进入结果集,但是值为null。

如果结果集像

那样最好
Person, Hair color
John,   brown
Peter,  null

如果可能的话,我想避免使用子查询,但如果无法使用连接,那么欢迎使用子查询。

1 个答案:

答案 0 :(得分:1)

外部联接将执行此操作:

select p.*, pa.value
from person p
  left join person_attributes pa
         on p.id = pa.person_id
        and pa.attribute = 'hair';

请注意,“outer joined”表的条件需要进入JOIN子句,而不是进入where子句。如果条件在where子句中,它将有效地将外连接转换为内连接。这是因为pa.attribute由于外连接而为空,并且where与空值不匹配,因此消除了实际应该保留在结果中的所有行。

SQFiddle基于您的示例:http://sqlfiddle.com/#!12/d0342/1