Retrieve a list of lists in one SQL statement

血红的双手。 提交于 2020-02-07 01:58:07

问题


I have two tables (say) Person and Parent with Parent-Person being many to one relationship, so a person can have many parents, direct and indirect (grandparents etc). Parent has foreign key personId and primary key of Person is of course, personId.

Person table
Id <PK>

Parent table
Id<PK>
ParentPersonId <FK into Person >

Person has rows with values PK 
1
2
3

Parent has rows with values
1, 2
1, 3
2, 3

so person 1 has parents 2, 3

I eapect to get List<Person>

[ {1, {2,3}}, {2, {3}}, {3} ]

I am using Spring Boot JDBC to query a MS SQL server database and I can get all parents for personId and of course, I can get a list of all persons in Person table. But is it possible in one SQL statement to retrieve a list of all persons and within class person, a List of person Id which are the result of the join with Parent table?

Or do I have to do it in 2 steps. Get a list of persons, then query the database for the list of parents of each person?

I am trying to do something like this but it says 'syntax error'.

 select ID as personId (select * from Parent where personId = parentPersonId) from Person

回答1:


Assuming your data in Parent table is not recursive (this table contains a row for each ancestor, direct or indirect), you can use a simple query:

select per.id, par.parentPersonId 
from Person per left join Parent par 
on per.id = par.id

If your data is recursive (apparently not, as 3 is both parent and grandparent for 1), you need to use a recursive-CTE query. See code in my follow-up question Is branch pruning possible for recursive cte query



来源:https://stackoverflow.com/questions/59939806/retrieve-a-list-of-lists-in-one-sql-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!