我在PostgreSQL数据库中有一些位置表:
var fullName = typeof(TestClass).AssemblyQualifiedName;
这描述了一个国家公园" X"它涵盖了A市和B市,即该公园有两个父亲和#34;在分层方案中。
当我进行联接查询时,我会为这个公园获得两行:
Table loc -- the places themselves
---------
| id | name
| 1 | Park X
| 2 | City A
| 3 | City B
Table locdad -- the hierarchical relationship between places
------------
| id | dad | loc
| 1 | 2 | 1
| 1 | 3 | 1
我想将结果合并到:
select l.id,l.name loc,l1.name dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1
| id | loc | dad
| 1 | Park X | City A
| 1 | Park X | City B
我该怎么做?
答案 0 :(得分:3)
尝试使用如下的array_agg函数:
String lineSeparator = System.getProperty("line.separator");
LOGGER.info("Person's name is {} .{}", person.getName(), lineSeparator);
这取决于你的postgres版本,但要用逗号分隔字符串 - 使用9.0+:
select l.id,l.name loc,array_agg(l1.name) dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1
GROUP BY l.id,l.name
或者这是8.4
select l.id,l.name loc,string_agg(l1.name, ', ') dad
from loc l
join locdad ld on ld.loc = l.id
join loc l1 on l1.id = ld.dad
where l.id=1
GROUP BY l.id,l.name