Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to select just 1 child table item for each parent record?
    primarykey
    data
    text
    <p>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 my question:</p> <pre><code> 'lists' table id updated share --- ---------- ----- 1 2013-07-11 1 2 2013-07-13 0 3 2013-07-15 1 4 2013-07-14 0 5 2013-07-14 1 'list_items' table id l_id description sort likes -- ---- ----------- ---- ----- 1 1 hello 0 3 2 1 goodbye 0 0 3 1 thanks 0 4 4 2 ok 0 0 5 3 love 0 2 6 3 hate 1 1 7 4 celebrate 0 0 8 5 party 0 1 9 5 summer 1 5 10 5 winter 2 2 </code></pre> <p>Now say I want to get the first item from each shared list (share = 1). By first I mean if the list items were sorted by 'sort'.</p> <p>The expected result based on the above data would be:</p> <pre><code>lists.id id l_id description sort likes -------- -- ---- ----------- ---- ----- 1 1 1 hello 0 3 3 5 3 love 0 2 5 8 5 party 0 1 </code></pre> <p><strong>Update:</strong> I struggled to get my head around the solutions provided by peterm and hims056 and while kayla's solution looked more like something I could follow it didn't return the correct results. Taking ideas from these solutions I had a crack at it myself and came up with</p> <pre><code> SELECT * FROM ( SELECT lists.id AS listid, lists.share, list_items.* FROM list_items, lists WHERE lists.id = l_id AND lists.share = 1 ORDER BY sort) q GROUP BY q.listid </code></pre> <p>This seems to work but as peterm points out, the values for the columns in select clause that are not part of group by clause may be ambiguous.</p> <p>I though someone would come up with a solution using <code>LIMIT</code> as that was the way I was thinking about doing it first. You can return the list ids which allow sharing simply by:</p> <pre><code>SELECT lists.id FROM lists WHERE share = 1 </code></pre> <p>and for a given list id you can return the top list item by:</p> <pre><code>SELECT lists.id AS listid, lists.share, list_items.* FROM list_items, lists WHERE lists.id = l_id AND lists.id = 1 ORDER BY sort LIMIT 1 </code></pre> <p>But is there a way to put these 2 statements together to return top list item for each list that allows sharing?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload