多个 LIKE 运算符 ORDER BY Strongest
Posted
技术标签:
【中文标题】多个 LIKE 运算符 ORDER BY Strongest【英文标题】:Multiple LIKE Operator ORDER BY Strongest 【发布时间】:2020-04-14 21:24:19 【问题描述】:我有以下疑问:
SELECT * FROM table_name
WHERE (genre LIKE '%romance%'
OR genre LIKE '%comedy%'
OR genre LIKE '%horror%')
ORDER BY *the column that has more*
或类似的东西
$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%')";
我的意思是,如果有一部电影具有这三种类型,我想首先获得它,否则我会获得浪漫与喜剧或浪漫与恐怖或喜剧与恐怖的电影。
【问题讨论】:
【参考方案1】:条件运算符在为真时返回1
,在为假时返回0
。所以把匹配的数量加起来。
ORDER BY (genre LIKE '%romance%')
+ (genre LIKE '%comedy%')
+ (genre LIKE '%horror%') DESC
DEMO
最好标准化您的表格。添加表movie_genre
like
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
);
然后你会做这样的查询:
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
【讨论】:
此外,您可以将每个LIKE
乘以一个常数,例如,赋予“浪漫”比“恐怖”更多的“重量”。以上是关于多个 LIKE 运算符 ORDER BY Strongest的主要内容,如果未能解决你的问题,请参考以下文章
使用 LIKE 字在 mySQL 中定义自定义 ORDER BY 顺序
MySQL查询关键字之select/where/group by/having/distinct/order by/limit/regexp/like