问题
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