Given these two tables
lists
| id | name | weight |
|---|---|---|
| 1 | Groceries | 0 |
| 2 | Pharmacy | 1 |
| 3 | Misc | 2 |
list_items
| id | list | weight |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 0 |
| 3 | 1 | 2 |
| 4 | 2 | 1 |
| 5 | 2 | 0 |
| 6 | 1 | 3 |
Can I construct a query that returns:
| id | name | items | totalNumberOfItems |
|---|---|---|---|
| 1 | Groceries | 2, 1, 3 | 4 |
| 2 | Pharmacy | 5, 4 | 2 |
| 3 | Misc | null | 0 |
Ie. all of the lists — regardless of whether they have items or not — sorted by weight, with the firs three items of each list (also sorted by the item's weight) concatenated and comma separated.
I have this so far:
However, as soon as I add a
LIMITto theLEFT JOINsubquery I get no results — so the join isn't capped at 3 and I can't seem to get the total count of items without messing it all up.