Mysql SQL连接三个表(一个是关系表)
需要一些查询方面的帮助。。我有三张桌子Mysql SQL连接三个表(一个是关系表),mysql,sql,join,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
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
谢谢好吧,这回答了你的原始问题。我不确定你现在在找什么
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'
,但这会降低性能。如果您已经知道人员id,则无需加入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
您可能正在查找组_concat():
这是针对mysql的,请检查各自DBMS中的组_concat()1)输出的列名是什么?2) 您是否只有这3个源?Hi Mosty-我当前的代码采用该结果集,并从结果集中添加每个源,并附加一个逗号(以输出到CSV)。为了解释,我把它放平了(我真的有大约110000人和20个来源)。我的查询的输出列名为“name”。如果添加了更多源,您是否正在寻找将输出动态列的查询?感谢您的回复。我已经尝试了我在问题中附加的问题。结果是我会在专栏中看到Gary(id:1)和Wikipedia。对于Gary来说,我想在一个单独的栏目中看到空的Wikipedia。这不一定是动态的——我的代码是每次调用的代码,并提取最新的源代码列表。因此,只需为一个人显示所有源代码,不管是null还是姓名。在这种情况下,您可能需要一个xml组函数—您使用什么RDBMS(据我所知,Oracle和最新的DB2支持这些RDBMS)BINGO。正是我想要的。非常感谢。
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