MySQL LIMIT and GROUP BY with JOIN
Is there a way to GROUP BY one tables column, but LIMIT by another in one query. Something like:
SELECT items.*, subitems.*
FROM items
LEFT OUTER JOIN subitems ON subitems.subitem_itemId = items.item_id
GROUP BY subitem.subitem_id
LIMIT 10
... but where the LIMIT 10 applies to the amount of item records, not actual rows. so i get 10 items, but unlimited subitems, therefore potentially more than开发者_开发百科 10 actual rows (or not if there are equal or less children than parents).
I can then loop through these in php and set up the parent/child relationships. Or is there a better way of doing this?
You have to use a sub-query for this:
SELECT items.*,subitems.*
FROM (
SELECT *
FROM items
LIMIT 10
) AS items
LEFT OUTER JOIN subitems ON subitems.subitem_itemId = items.item_id
GROUP BY subitem.subitem_id;
精彩评论