Can you return different values for multiple rows on the same join?
I have two tables:
Parent Information
Child Information
both are structured (almost) the same with a few nuances.
The table structures are as follows:
Parent
ID | First | Last | DOB | Address
-------------------------------------------------
1 | John | Doe | 1980-01-01 | 123 street
Dependents
ParentID | Type | First | Last | DOB
--------------------------------------------------
1 | Spouse | Jane | Doe | 1981-02-01
1 | Child | Mike | Doe | 1999-08-01
1 | Child | Zoe | Doe | 2002-04-01
I want to build a query (ideally single call with joins which returns the following:
Table Results
First | Last | Type | DOB | Address
----------------------------------------------------------------
John | Doe | Parent | 1980-01-01 | 123 Street
Jane | Doe | Spouse | 1981-02-01 | 123 Street
Mike | Doe | Child | 1999-08-01 | 123 street
Zoe | Doe | Child | 2002-开发者_如何学编程04-01 | 123 Street
I suppose I could build the originally subquery with a LEFT JOIN on the dependents table (not all parents have dependents) then run a primary query which filters that table, however - when i do this, the query takes over a full minute to produce. (my tables change hundreds of times a day so keeping an index of the tables is not really an option as I'd have to rebuild constantly).
UPDATE
The more I think about it even the left join would not work necessarily because the parent information and first set of dependent information would reside on the same row from the subquery (and in turn make it 'impossible' for the primary query to filter the single row into multiple).
Any ideas?
SELECT t.First, t.Last, t.Type, t.DOB, t.Address
FROM (SELECT ID, First, Last, 'Parent' as Type, DOB, Address, 1 as SortKey
FROM Parent
UNION ALL
SELECT p.ID, d.First, d.Last, d.Type, d.DOB, p.Address,
CASE WHEN d.Type = 'Spouse' THEN 2 ELSE 3 END as SortKey
FROM Dependents d
INNER JOIN Parent p
ON d.ParentID = p.ID) t
ORDER BY t.ID, t.SortKey
精彩评论