多个 LIKE 运算符 ORDER BY Strongest

Multiple LIKE Operator ORDER BY Strongest

我有以下查询:

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%')";

我的意思是,如果有一部电影具有这三种类型,我想先得到它,否则我会得到具有浪漫和喜剧或浪漫和恐怖或喜剧和恐怖的电影。

条件运算符 returns 1 为真时,0 为假时。所以把比赛的数量加起来。

ORDER BY (genre LIKE '%romance%')
        + (genre LIKE '%comedy%')
        + (genre LIKE '%horror%') DESC

DEMO

最好规范化您的 table。加个tablemovie_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
);

然后你会做这样的查询:

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