我正在使用mysql / mariadb。
我想做什么:为每个id
获取name
,private
,Group
/然后获取每个Video
的数量Group
1}} /然后获取每个Video
的最后20 Group
个。
现在,我使用三个单独的SQL查询,然后每次为每个相应的id运行它。有没有办法将三个SQL查询合并为一个,并在ID列表上运行它们?
例如,在1,2,3组:
Executing (default): select `id`, `name`, `private` from `Groups` where `id` = '1' limit 1
Executing (default): select `id`, `name`, `private` from `Groups` where `id` = '2' limit 1
Executing (default): select `id`, `name`, `private` from `Groups` where `id` = '3' limit 1
Executing (default): select count(*) from `Videos` where `GroupId` = '1' and `live` = true
Executing (default): select count(*) from `Videos` where `GroupId` = '2' and `live` = true
Executing (default): select count(*) from `Videos` where `GroupId` = '3' and `live` = true
Executing (default): select `id`, `file` from `Videos` where `GroupId` = '1' and `live` = true order by `id` desc limit 20
Executing (default): select `id`, `file` from `Videos` where `GroupId` = '2' and `live` = true order by `id` desc limit 20
Executing (default): select `id`, `file` from `Videos` where `GroupId` = '3' and `live` = true order by `id` desc limit 20
答案 0 :(得分:0)
使用IN
Executing (default): (SELECT `id`, `name`, `private` FROM `Groups` WHERE`id` = '1' LIMIT 1)
UNION ALL
(SELECT `id`, `name`, `private` FROM `Groups` WHERE`id` = '2' LIMIT 1)
UNION ALL
(SELECT `id`, `name`, `private` FROM `Groups` WHERE`id` = '3' LIMIT 1)
Executing (default): SELECT count(*)
FROM `Videos`
WHERE `GroupId` IN ('1', '2', '3') AND `live` = true
Executing (default): (SELECT `id`, `file` FROM `Videos` WHERE`GroupId` = '1' AND `live` = true ORDER BY `id` DESC LIMIT 20)
UNION ALL
(SELECT `id`, `file` FROM `Videos` WHERE`GroupId` = '2' AND `live` = true ORDER BY `id` DESC LIMIT 20)
UNION ALL
(SELECT `id`, `file` FROM `Videos` WHERE`GroupId` = '3' AND `live` = true ORDER BY `id` DESC LIMIT 20)