patternMinor
Efficient way to join two tables with one to many relationship
Viewed 0 times
tableswithefficientwayjointwoonemanyrelationship
Problem
This is interview question asked to me in interview and i was not able to answer. Please help..
What is the most efficient way to join two table with one to many relationship between them
What is the most efficient way to join two table with one to many relationship between them
Solution
Most effective way is to use an INNER JOIN, like this:
And when you need aggregates on child level, you can add a GROUP BY and SUM and/or AVG or other aggregate functions:
SELECT *
FROM Parent P
INNER JOIN Child C
ON C.ParentId = P.ParentIdAnd when you need aggregates on child level, you can add a GROUP BY and SUM and/or AVG or other aggregate functions:
SELECT P.Name
, P.Address
, SUM(C.Amount)
FROM Parent P
INNER JOIN Child C
ON C.ParentId = P.ParentId
GROUP BY P.Name
, P.AddressCode Snippets
SELECT *
FROM Parent P
INNER JOIN Child C
ON C.ParentId = P.ParentIdSELECT P.Name
, P.Address
, SUM(C.Amount)
FROM Parent P
INNER JOIN Child C
ON C.ParentId = P.ParentId
GROUP BY P.Name
, P.AddressContext
StackExchange Database Administrators Q#118693, answer score: 9
Revisions (0)
No revisions yet.