Skip to content Skip to sidebar Skip to footer

How To Select Just 1 Child Table Item For Each Parent Record?

I have a table of lists and a table of list items. I want to formulate a query to select just one list item for each item in the lists table. Here's some simple data to illustrate

Solution 1:

SELECT lists.id, list_items.id, l_id, description, sort, likes 
  FROM (SELECT * FROM lists WHERE share = 1) lists 
  LEFT JOIN (SELECT * FROM list_items GROUPBY l_id) list_items 
  ON  lists.id = l_id

Solution 2:

UPDATED To ensure getting first per group with order by sort try

SELECT q.l_id list_id, q.id, i.description, i.sort, i.likes 
  FROM 
(
  SELECT l_id, id, @n := IF(@g= l_id, @n+1, 1) n, @g := l_id g
    FROM 
  (
    SELECT i.l_id, i.id
      FROM list_items i JOIN lists l
        ON i.l_id = l.id 
     WHERE l.share =1ORDERBY l_id, sort, id
  ) b CROSSJOIN (SELECT@n :=0, @g :=0) a
  HAVING n =1
) q JOIN list_items i 
   ON q.id = i.id

Sample output:

| LIST_ID | ID | DESCRIPTION | SORT | LIKES |
---------------------------------------------
|       1 |  1 |       hello |    0 |     3 |
|       3 |  5 |        love |    0 |     2 |
|       5 |  8 |       party |    0 |     1 |

Here is SQLFiddle demo

Solution 3:

Since you want to get minimum list_items.id sorted by list_items.sort you need to perform double nested query like this:

SELECT tbl.l_id list_id, tbl.minID, li.description, li.sort, li.likes 
FROM list_items li
JOIN
(
    SELECT l.l_id,MIN(l.id) minID FROM list_items l
    JOIN
    (
        SELECT li.l_id,MIN(li.sort) sort FROM list_items li
          JOIN lists l ON li.l_id = l.id WHERE l.share = 1GROUPBY li.l_id
    ) l2
    ON l.l_id = l2.l_id
    AND l.sort = l2.sort
    GROUPBY l.l_id
) tbl
ON  li.id = tbl.minID;

Post a Comment for "How To Select Just 1 Child Table Item For Each Parent Record?"