tags:

views:

865

answers:

2

I have this query and I need to include another join on a table called "likes" where updates.id = likes.update_id. There will be 0 or more matches on this join.

"SELECT * FROM users 
INNER JOIN updates ON users.remote_id=updates.owner_id 
ORDER BY updates.status_time DESC LIMIT 50"

This is probably fairly simple, but I haven't been able to find any examples for this kind of query.

The situation is basically that I'm displaying a list of items. I do a join on the users table to grab the user who created each item. I also need to do a join on the "likes" tables to display the 0+ people who liked each item.


EDIT: My Solution

Ok, here's the successful join and combining of duplicate results (due to the fact that there are multiple "likes" for each update) using GROUP_CONCAT.

"SELECT   users.*,updates.update_id,updates.content,updates.status_time,
GROUP_CONCAT(likes.liker SEPARATOR ',') AS liked_by 
FROM updates 
LEFT OUTER JOIN likes ON updates.update_id = likes.update_id 
JOIN users ON users.remote_id = updates.owner_id 
GROUP BY updates.update_id 
ORDER BY updates.status_time DESC 
LIMIT 200"
+2  A: 
SELECT * FROM users 
LEFT OUTER JOIN updates ON users.remote_id=updates.owner_id
INNER JOIN likes ON <join condition here>
ORDER BY updates.time DESC LIMIT 50

Will that work?

If not, can you clarify what exactly your question is? Does the query you have not work?

Kalium
If there are zero or more matches, think "LEFT OUTER JOIN".
le dorfier
Ah. That makes more sense, then.
Kalium
See my edit in the main post. Let me know if that is unclear. I'm a bit tired..
makeee
A left join in mysql is always an outer join, and just a join is always an inner join. No need to use 'outer' or 'inner' iirc.
apphacker
No need, but it makes the behavior more explicit.
Kalium
A: 

if you have a 1 to n relation the you should use a LEFT JOIN , i mean if there's only 1 user and many likes.user_id you should doit with the following way

"SELECT * FROM users LEFT JOIN updates ON (users.remote_id=updates.owner_id) ORDER BY updates.time DESC LIMIT 50"

this way you'd get all the updates from a certain user :)

cheers

PERR0_HUNTER