MySQL 连续查找上一集?

标签 mysql sql

SET @current_episode = 1;
SET @current_season = 2;
SET @current_serial = 2;

SELECT * FROM `episode` _episode 
    LEFT JOIN season _season ON _episode.season_id = _season.id
    LEFT JOIN serial _serial ON _season.serial_id  = _serial.id 
WHERE 

    (_episode.episode < @current_episode AND _season.season = @current_season)
        OR 
    (_episode.episode > @current_episode AND _season.season = (@current_season - 1))

ORDER BY _season.season DESC, _episode.episode ASC
LIMIT 0,1

剧集表结构:

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| season_id   | int(11)      | YES  | MUL | NULL    |                              |
| poster_id   | int(11)      | YES  | MUL | NULL    |                |
| episode     | int(11)      | NO   |     | NULL    |                              |
+-------------+--------------+------+-----+---------+----------------+

季节表结构:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| serial_id  | int(11)      | YES  | MUL | NULL    |                |
| season     | int(11)      | NO   |     | NULL    |                |

串口表结构:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |

我的SQL无法正确找到前一集 因为如果我尝试按季节 DESC 找到它,它将是正确的,而剧集编号不是本季的第一集。

最佳答案

查找上一集

只需在 OR 之后更新 WHERE 子句,并在 _episode.episode 上也对 DESC 进行排序

SET @current_episode = 1;
SET @current_season = 2;
SET @current_serial = 2;

SELECT * FROM `episode` _episode 
    LEFT JOIN season _season ON _episode.season_id = _season.id
    LEFT JOIN serial _serial ON _season.serial_id  = _serial.id 
WHERE 

    (_episode.episode < @current_episode AND _season.season = @current_season)
        OR 
    (_season.season < @current_season)

ORDER BY _season.season DESC, _episode.episode DESC
LIMIT 0,1

关于MySQL 连续查找上一集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42144441/

相关文章:

java - 从 java 执行过程时出现 JDBC 连接错误

mysql - 显示所有类型,不仅在MySQL中发送

php - MYSQL 错误 1064 在 select 子句中

mysql - 使用 phpMyAdmin 访问多个远程服务器

Mysql查询 explode 并计数

sql - Null是否大于任何日期数据类型?

sql - HTML 实体应该如何存储在 SQL Server 上?

SQL 查询以过滤特定记录计数的记录

sql - Impala/SQL 如何将所有其他字段放在 group by 语句中?

php - 如何将 PHP radius 函数与多个变量一起使用?