我在桌面上运行一个简单的LIKE搜索,但由于某些原因我似乎无法获得多个结果。在下面的查询示例中,我包括“永不退缩”和“灵魂冲浪者”之类的单词,但我只获得了其中一部电影。我和我的数据库一起有这些电影。
以下是查询:
SELECT movies . * , GROUP_CONCAT( categories.name ) AS categories, GROUP_CONCAT( categories.id ) AS categories_id
FROM movies
LEFT JOIN movies_categories ON ( movies.id = movies_categories.movie_id )
LEFT JOIN categories ON ( movies_categories.category_id = categories.id )
WHERE movies.movie_title LIKE '%surfer%'
OR movies.movie_title LIKE '%date%'
OR movies.movie_title LIKE '%never%'
OR movies.movie_title LIKE '%back%'
OR movies.movie_title LIKE '%down%'
OR movies.movie_title LIKE '%surfer%'
OR movies.movie_title LIKE '%soul%'
OR movies.movie_title LIKE '%the%'
OR movies.movie_title LIKE '%transporter%'
LIMIT 0 , 30
我原以为查询一定有问题,否则会返回所有结果?我知道有些词语在类似的条款中是重复的,但这并不重要。我错过了什么吗?
我使用的group_concat()函数导致查询只返回一个结果,并连接所有电影的类别和category_id。我刚刚删除了group_concat(),现在可以正常工作了。
答案 0 :(得分:4)
您使用的是GROUP_CONCAT
聚合函数,并将结果折叠为一个。
添加GROUP BY
子句:
SELECT movies . * , GROUP_CONCAT( categories.name ) AS categories, GROUP_CONCAT( categories.id ) AS categories_id
FROM movies
LEFT JOIN movies_categories ON ( movies.id = movies_categories.movie_id )
LEFT JOIN categories ON ( movies_categories.category_id = categories.id )
WHERE movies.movie_title LIKE '%surfer%'
OR movies.movie_title LIKE '%date%'
OR movies.movie_title LIKE '%never%'
OR movies.movie_title LIKE '%back%'
OR movies.movie_title LIKE '%down%'
OR movies.movie_title LIKE '%surfer%'
OR movies.movie_title LIKE '%soul%'
OR movies.movie_title LIKE '%the%'
OR movies.movie_title LIKE '%transporter%'
GROUP BY
movies.id
LIMIT 0 , 30
另外,如果您的movies
表格为MyISAM
,则可以运行此代码:
SELECT movies.*,
GROUP_CONCAT(categories.name) AS categories,
GROUP_CONCAT(categories.id) AS categories_id
FROM movies
LEFT JOIN
movies_categories
ON movies_categories.movie_id = movies.id
LEFT JOIN
categories
ON categories.id = movies_categories.category_id
WHERE MATCH(movie_title) AGAINST ("never back down" IN BOOLEAN MODE)
GROUP BY
movies.id
LIMIT 0, 30
如果您创建FULLTEXT
索引,此查询将运行得更快:
CREATE FULLTEXT INDEX fx_movies_title ON movies (movie_title)