views:

186

answers:

3

Basically I have a mysql query something like the following:

mysql_query("SELECT n.title, v.value FROM posts n INNER JOIN votes v ON n.id = v.id");

And what I need to do is to grab the title from the posts table and the current vote value from the votes table.

At the moment, votes aren't stored into the votes table unless a vote happens. So all posts with 0 votes aren't in the votes table.

This causes an error that it's trying to get the title AND vote value where the post id = the vote value id. If there isn't any record in the votes table, then value should return as NULL or 0 but at the moment the whole query returns as null so I can't even return the title.

How can I fix this all in one query? I don't want to have to use multiple queries... Thanks :)

+3  A: 

Use a left join instead of an inner

An inner join requires matching rows from the table on both sides of the join.

A left join (or left outer join to use its full name) selects all rows from the left table, and then matching rows from the right, returning null values if there are no matching rows in the right table, just like you are asking for.

(There are also right outer joins, but the same effect can be achieved by changing the conditions around in the ON clause)

benlumley
Show's how much I know! Thanks a LOT!
NJ
A: 
SELECT n.title, v.value FROM posts n LEFT JOIN votes v ON n.id = v.id
Ólafur Waage
A: 

SELECT n.title, v.value FROM posts as n, votes as v WHERE n.id = v.id

Try that.

J.J.
That's what I had before and it worked before, so by default MySQL must be using LEFT JOIN. It was only now that when I rewrote the query I decided to use INNER JOIN which messed everything up. Thanks :)
NJ
Please do it the other way. The explicit JOIN syntax is much easier to follow, and as evidenced here, it's not always clear what kind of join you're getting in this syntax. On other SQL back-ends you would not get a left join as written.
Joe