gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:51:55 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com