If I have a table of categories with a featured row that is default 0, then 1/2/3/4/5/6 to feature six categories in the order they should be displayed.
Could I use the category id from the each of the six featured to select 4 videos from the video table with corresponding categoryId's in one query and then separate the result out with foreach's?
Then return them and do foreach result as category then foreach category as videoList
SELECT id, title
FROM videos
WHERE category = (SELECT id FROM category WHERE featured > 0)
LIMIT 4
to return something like this:
foreach($result as $categoryVideos):
echo $categoryVideos[categoryName];
foreach($categoryVideos as $video):
echo $video[title];
endforeach;
endforeach;
I know it needs joins etc but am I making this way too complicated? I'm blaming my blank mind on a lack of sleep as I'd usually be the one answered a question like this ..
It's more complicated because I'm trying to pass all this data from a model to the controller in one go as $result?
Your basic approach will work, but you have a few problems with your SQL:
ORDERBY
to tell SQL what order you want the records in. If I understand correctly the category ranking is in the category
table. If that's the case, you need ORDERBY
and the limit in the subquery, eg SELECT id FROM category WHERE featured > 0 ORDERBY featured LIMIT 4
. WHERE category = (SELECT...
syntax is wrong. Replace =
with IN
. You're trying to fetch 4 rows from each of 6 categories, right? For a total of 24 rows?
The first answer to this question is probably applicable to your case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.