【数据库专题】Lettcode SQL架构题 620. 有趣的电影

一 题目 620. 有趣的电影

某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。

作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

例如,下表 cinema:

+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   1     | War       |   great 3D   |   8.9     |
|   2     | Science   |   fiction    |   8.5     |
|   3     | irish     |   boring     |   6.2     |
|   4     | Ice song  |   Fantacy    |   8.6     |
|   5     | House card|   Interesting|   9.1     |
+---------+-----------+--------------+-----------+
对于上面的例子,则正确的输出是为:

+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   5     | House card|   Interesting|   9.1     |
|   1     | War       |   great 3D   |   8.9     |
+---------+-----------+--------------+-----------+

二 官网题解:

方法:使用 MOD() 函数

我们可以使用 mod(id,2)=1 来确定奇数 id,然后添加 description != ‘boring’ 来解决问题。

MySQL
select *
from cinema
where mod(id, 2) = 1 and description != 'boring'
order by rating DESC;

三 改造官网题解:

3.1 题解一

select * from from cinema 
where id&1 and description<>'boring' 
order by rating desc

3.2 题解二

SELECT * FROM cinema
WHERE description != 'boring' AND id % 2 = 1
ORDER BY rating DESC;

四 MySQL 中判断奇数的 6 种方法:

  • mod(x, 2) = 1 ,如果余数是 1 就是奇数。
  • power(-1, x) = -1 , 如果结果是 -1 就是奇数
  • x % 2 = 1 ,如果余数是 1 就是奇数。
  • x & 1 = 1 ,如果是 1 就是奇数(1代表true,0代表false)
  • x regexp ‘[1, 3, 5, 7, 9]$’ = 1 如果为 1 就是奇数
  • x>>1<<1 != x 如果右移一位在左移一位不等于原值,就是奇数

猜你喜欢

转载自blog.csdn.net/weixin_42469135/article/details/125654317