Wednesday, April 28, 2010

How to limit joined records in MySQL

I have to tables with one-to-many relationship. I needed to select all from the master table and join only one record which contains the oldest date.
The solution is:
SELECT parent.*,
       c1.*
  FROM parent
       JOIN child c1
          ON c1.parent_id = parent.id
       LEFT JOIN child c2
          ON c2.parent_id = c1.parent_id AND c2.sort < c1.sort -- field to determine the order (maybe whatever you want)
GROUP BY parent.id,
         parent.name,
         c1.id,
         c1.name
HAVING COUNT(c2.id) < 1 -- limitation of joined records
ORDER BY parent.name, c1.name;
I found it there.

No comments:

Post a Comment

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