views:

127

answers:

3

I have this query in MySQL:

SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT OUTER JOIN `jos_hp_properties2` pr7 ON pr7.property=pr.id
WHERE pr7.field=23

The jos_hp_properties table has 27 rows but the query only returns one. Based on this question I think it may be because of the WHERE clause. The jos_hp_properties2 table has fields id, property, field, value, where field is a foreign key to a third table (which I don't need to get data from).

Is there a way to select all the rows from the first table, including the value from table #2 where the field is 23 (or NULL if there is no field 23)?

+2  A: 

Sure. Move the WHERE condition to the JOIN:

SELECT pr.*, pr7.value AS `room_price_high`
  FROM `jos_hp_properties` pr
       LEFT JOIN `jos_hp_properties2` pr7 
       ON pr7.property=pr.id
   AND 
       pr7.field=23
Adam Bernier
Thanks! The answer in the question I linked actually explains this, but for some reason it didn't make sense first time I read it...
DisgruntledGoat
Cheers mate. I'd forgotten to upvote your question for being useful and clear, but I did now.
Adam Bernier
A: 

Try this:

SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT OUTER JOIN `jos_hp_properties2` pr7 ON pr7.property=pr.id
WHERE (pr7.field=23 OR pr7.field is null)
MJB
This isn't quite the optimal query - see the other answers where the pr7 criteria are moved to the join.
Jeff Meatball Yang
Yeah, I saw that when I was typing it and should have changed it, but I was feeling lazy. This question reminds me of all the programmers who specifically exclude rows and then expect them to magically reappear because they said "outer join."
MJB
+2  A: 

You must place the pr7 criteria in the join, not in the where clause. The where clause works on the entire result set AFTER the join has been performed.

SELECT pr.*, pr7.value AS `room_price_high`
FROM `jos_hp_properties` pr
LEFT OUTER JOIN `jos_hp_properties2` pr7 ON pr7.property=pr.id and pr7.field=23
Jeff Meatball Yang