WHERE 子句中的 MYSQL MIN

标签 mysql where-clause min

好的,所以我正在开发一个家庭影院系统,为了显示电视剧列表,我选择了第一季的第一集并显示该集的相关信息,然后您可以向下钻取给其他人。

这样我就可以将所有电影和所有电视节目保存在一个表中,这使得播放功能更加容易。

问题是,有些系列我在数据库中没有第一集,但我希望它们无论如何都会出现,所以我想选择最小的季节/系列而不是第一集。

我无法将 MIN 放在 select 子句中,因为它只选择一个系列,并且我无法将 LEAST 放在 WHERE 子句,因为它说它只是一个元素,因为它们的分组方式,而且我不能使用 LIMIT 因为它只会选择一个系列。

有没有办法在没有多个复杂子查询的情况下做到这一点?

这是我目前使用的查询,CASE 子句是从系列标题中删除 A/An/The,以实现正确的字母顺序:

SELECT *, CASE when substring(series,1,4) = 'The ' then substring(series, 5)
               when substring(series,1,3) = 'An ' then substring(series, 4)
               when substring(series,1,2) = 'A ' then substring(series, 3)
               else series END AS sorttitle 
FROM Theater.Videos WHERE type='TV' and season=1 and episode=1 ORDER BY sorttitle ASC

这基本上就是我想要的:

SELECT *, CASE when substring(series,1,4) = 'The ' then substring(series, 5)
               when substring(series,1,3) = 'An ' then substring(series, 4)
               when substring(series,1,2) = 'A ' then substring(series, 3)
               else series END AS sorttitle 
FROM Theater.Videos WHERE type='TV' and season=MIN(season) and episode=MIN(episode) ORDER BY sorttitle ASC

最佳答案

尝试这些查询(经过适当修改后)...

要获取所有系列的列表以及第一(分钟)季的第一集,请使用此...

select distinct v1.*
from videos v1,
    (select series, min(season) as min_season from videos group by series) as v2,
    (select series, season, min(episode) as min_episode from videos group by series, season) as v3
where v1.series = v2.series
and v1.season = v2.min_season
and v2.series = v3.series
and v2.min_season = v3.season
and v1.episode = v3.min_episode

要获取所有系列的列表以及每个季节的第一集,请使用此...

select distinct v1.*
from videos v1,
    (select series, season, min(episode) as min_episode from videos group by series, season) as v3
where v1.series = v3.series
and v1.season = v3.season
and v1.episode = v3.min_episode

关于WHERE 子句中的 MYSQL MIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17938384/

相关文章:

mysql - Rails 生产 : No such file or directory - Error opening database in production. 日志

mysql - 迁移以创建表引发 Mysql2::Error: 表不存在

php - 数组中的复选框没有值

mysql - SELECT 从同一表中获取两个条目,按日期区分,在一行中

mysql - 如何创建一个sql脚本来考虑两列?

sql - PostgreSQL 查询 WHERE 日期大于 3 年

html - 如何缩小 HTML 代码?

java - 为什么 JDBC 驱动程序将准备好的语句保持在连接级别?

r - 在 R 中添加最小行

java - 如何从通用数组列表中找到最小值?