Thursday, April 28, 2011

MYSQL one to many JOIN

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"
From stackoverflow
  • 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?

    le dorfier : If there are zero or more matches, think "LEFT OUTER JOIN".
    Kalium : Ah. That makes more sense, then.
    makeee : See my edit in the main post. Let me know if that is unclear. I'm a bit tired..
    apphacker : 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.
    Kalium : No need, but it makes the behavior more explicit.
  • 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

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.