SQL连接三个表(一个是关系表)

时间:2012-03-22 19:39:46

标签: mysql sql join

需要一些查询帮助..我有三个表。

Source
id      name
1       Other
2       Website
3       Wikipedia

Person
id      name
1       Tom
2       Lewis
3       Gary

person_source
person_sources_id  source_id
1                   2
1                   3
3                   3

我想构建一个查询,为每个源显示一个人和一个列 - 显示关系中存在的源名称,如果不存在则显示null:

output (for Tom)
-name-
null
Website
Wikipedia

我有以下查询,但它给了我附加到联系人的来源,没有空值..

    rs2 = s2.executeQuery("select distinct source.name "+
                        "from person left join person_source "+
                        "on person_source.person_sources_id = "+rs.getLong("id")+" join source "+
                        "on source.id = person_source.source_id");

我的代码是Tom的当前输出:

Output (for Tom)
-name-
Website
Wikipedia

由于

3 个答案:

答案 0 :(得分:2)

好吧,这会回答您的原始问题。我不确定你现在在寻找什么。

select p.name,
  max(if(s.id = 1, s.name, null)) Other,
  max(if(s.id = 2, s.name, null)) Website,
  max(if(s.id = 3, s.name, null)) Wikipedia
from source s
left join person_source ps on s.id = ps.source_id
right join person p on p.id = ps.person_sources_id
group by p.name
order by p.id

结果:

+-------+-------+---------+-----------+
| NAME  | OTHER | WEBSITE | WIKIPEDIA |
+-------+-------+---------+-----------+
| Tom   |       | Website | Wikipedia |
| Lewis |       |         |           |
| Gary  |       |         | Wikipedia |
+-------+-------+---------+-----------+

您可以将s.id = 1替换为s.name = 'Other',但效果会更差。

答案 1 :(得分:1)

如果您已经知道该人,则不需要加入person

select case when person_source.id is not null
            then source.name
       end "name"
from source
left join person_source
  on source.id = person_source.source_id
  and person_source.person_sources_id = :id
order by source.id

答案 2 :(得分:0)

您可能正在寻找group_concat():

select person.name as person,  group_concat(source.name) as source_list
 from person
 left join person_source as ps on ( ps.person_source_id=person.id) 
 left join source on source.id = ps.source_id 
 group by person.id

这是针对mysql的,请检查各个DBMS的group_concat()