问题
I have the following query:
SELECT * FROM table_name
WHERE (genre LIKE '%romance%'
OR genre LIKE '%comedy%'
OR genre LIKE '%horror%')
ORDER BY *the column that has more*
OR SOMETHING LIKE THAT
$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%')";
I mean if there is a movie has these three genres I want to get it first else I get movie which has romance and comedy or romance and horror or comedy and horror.
回答1:
A conditional operator returns 1
when it's true, 0
when it's false. So add up the number of matches.
ORDER BY (genre LIKE '%romance%')
+ (genre LIKE '%comedy%')
+ (genre LIKE '%horror%') DESC
DEMO
It would be better to normalize your tables. Add a table 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
);
Then you would do a query like:
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
回答2:
SELECT * FROM movies
WHERE (genre LIKE '%romance%'
OR genre LIKE '%comedy%'
OR genre LIKE '%horror%')
ORDER BY (genre LIKE '%romance%')
+ (genre LIKE '%comedy%')
+ (genre LIKE '%horror%') DESC
Thank you so much Barmar
来源:https://stackoverflow.com/questions/61217482/multiple-like-operator-order-by-strongest