Ale*_*oss 0 mysql sql sql-order-by sql-like
我有以下查询:
SELECT * FROM table_name
WHERE (genre LIKE '%romance%'
OR genre LIKE '%comedy%'
OR genre LIKE '%horror%')
ORDER BY *the column that has more*
Run Code Online (Sandbox Code Playgroud)
或类似的东西
$sql = "SELECT * FROM table WHERE
(genre LIKE '%romance%' AND genre LIKE '%comedy%' AND genre LIKE '%horror%')
#If result < 12
(genre LIKE '%romance%' AND genre LIKE '%comedy%') OR (genre LIKE '%romance%' AND genre LIKE '%horror%') OR (genre LIKE '%comedy%' AND genre LIKE '%horror%')
#If result < 12
(genre LIKE '%romance%' OR genre LIKE '%comedy%' OR genre LIKE '%horror%')";
Run Code Online (Sandbox Code Playgroud)
我的意思是,如果有一部电影有这三种类型,我想先得到它,否则我会得到有浪漫和喜剧或浪漫和恐怖或喜剧和恐怖的电影。
条件运算符1在它为真0时返回,当它为假时返回。所以把匹配的数量加起来。
ORDER BY (genre LIKE '%romance%')
+ (genre LIKE '%comedy%')
+ (genre LIKE '%horror%') DESC
Run Code Online (Sandbox Code Playgroud)
规范化你的表格会更好。添加一个表,movie_genre如
CREATE TABLE movie_genre (
movie_id INT(11) NOT NULL, # foreign key to movie.id
genre_id INT(11) NOT NULL # foreign key to genre.id
);
Run Code Online (Sandbox Code Playgroud)
然后你会做一个查询,如:
SELECT m.*
FROM movie AS m
JOIN movie_genre AS mg ON m.id = mg.movie_id
JOIN genre AS g ON g.id = mg.genre_id
WHERE g.name IN ('comedy', 'romance', 'horror')
GROUP BY m.id
ORDER BY COUNT(*) DESC
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |