Reputation: 11002
Simple MySQL tables with matching ID values across tables:
table 1;
pid, firstname
table 2;
id, pid, property, value
Lets say there is one person entry in table 1:
pid: 1
firstname: fred
For each person there are multiple table 2 entries:
pid: 1
property: likes cats?
value: no
pid: 1
property: eye colour
value: orange
pid: 1
property: favourite food
value: sox
I want to select just two of the many table two entries, say the eye colour and favour food entries for a given person ID. What kind of outer join can achieve this?
SELECT `t1`.name
FROM `table1` AS t1
LEFT JOIN `table2` t2 ON `t1`.pid = `t2`.pid
WHERE `t1`.pid = 1
AND `t2`.property = 'eye colour'
I'm stuck here, how to get two rows from table2 and include favour food also? (Before anyone says it, no I can't change the structure of this database).
Thanks for reading.
Upvotes: 2
Views: 103
Reputation: 6817
How about this?
SELECT t.name, t.value, t3.value
FROM
(SELECT t1.name, t2.value, t1.pid
FROM table1 t1
LEFT JOIN table2 t2 ON t1.pid = t2.pid
WHERE t1.pid = 1
AND t2.property = 'eye colour') t
LEFT JOIN table2 t3 ON t.pid = t3.pid
WHERE t.pid = 1
AND t3.property = 'favourite food'
This will also work for people who don't have an 'eye colour' or 'favourite food' entry
Upvotes: 2
Reputation: 76537
You need to left join twice:
SELECT
t1.name
,t2a.value as eye_color
,t2b.value as fav_food
FROM table1 t1
LEFT JOIN table2 t2a ON (t1.pid = t2a.pid AND t2a.property = 'eye colour')
LEFT JOIN table2 t2b ON (t1.pid = t2b.pid AND t2b.property = 'fav food')
WHERE t1.pid = 1
Upvotes: 5
Reputation: 9319
If you want to do this with one query then you should use INNER JOIN but i'm not recommending this. If i were you i would select first the person then i would create another query to recieve the necessary table2 entries. Try both of my solutions you could choose the right one for you.
Upvotes: -1
Reputation: 9860
How about something like:
SELECT t1.name, t2.property, t2.value
FROM table2 t2
INNER JOIN table1 t1 ON t1.pid = t2.pid
WHERE t2.pid = 1
AND t2.property IN ('eye colour','favourite food')
Or you just wanted the first two however MySQL indexed it:
SELECT t1.name, t2.property, t2.value
FROM table2 t2
INNER JOIN table1 t1 ON t1.pid = t2.pid
WHERE t2.pid = 1
LIMIT 2
There's no real reason to use a LEFT JOIN here, since there should always be an associated pid
defined in table1
.
Upvotes: 4