mysql - 是否可以组合这些 SQL select 语句?

标签 mysql sql

我正在使用 mysql/mariadb。

我想做的:为每个 Group 获取 idnameprivate/然后获取每个 Group 中的 Video 数量/然后为每个 Group 获取最后 20 个 Video

现在,我使用三个单独的 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

最佳答案

使用 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)

关于mysql - 是否可以组合这些 SQL select 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939368/

相关文章:

mysql - SQL:不允许从函数返回结果集

mysql - SQL:在分隔符与分隔符本身之间进行选择,插入其他列并删除字符串

mysql - 获取所有行在列中显示相同的值

mysql - 还选择空值

php - 如何阻止查询结果在列之间拆分单个行的数据?

mysql - 编写 SQL 查询,同时选取除三列中具有指定值的行之外的所有行

mysql - SQL - 一些行的总和,减去其他行的总和

sql - 在 postgresql 中选择查询 >= jsonb 列值

sql - 获取每个日期最接近的记录

php - 检查 Joomla php 函数中是否存在查询结果?