我有3张桌子:
Category +-------------+----------+ | category_id | name | +-------------+----------+ | 1 | Business | +-------------+----------+ | 2 | Sport | +-------------+----------+ | 3 | Games | +-------------+----------+
News +----+----------------------+ | id | title | +----+----------------------+ | 1 | Bitcoin Price | +----+----------------------+ | 2 | Sport | +----+----------------------+ | 3 | Electric flying cars | +----+----------------------+
CatNews +---------+--------+ | news_id | cat_id | +---------+--------+ | 1 | 1 | +---------+--------+ | 2 | 3 | +---------+--------+ | 2 | 2 | +---------+--------+
SELECT *, GROUP_CONCAT(cat.name) FROM news n JOIN CatNews c ON n.id = c.newsid JOIN category cat ON c.cat_id = cat.category_id GROUP BY n.id;
使用此功能,我收到
返回id | title | news_id | cat_id | name | GROUP_CONCAT(cat.name) 2 | Electric flying cars | 2 | 3 | Sport | Sport, Games
问题出在我使用时:
SELECT *, GROUP_CONCAT(cat.name) FROM news n JOIN CatNews c ON n.id = c.newsid JOIN category cat ON c.cat_id = cat.category_id AND cat.name LIKE '%Games%' GROUP BY n.id
返回我:
id | title | news_id | cat_id | name | GROUP_CONCAT(cat.name) 2 | Electric flying cars | 2 | 3 | Games | Games
如何使用LIKE查找事件但保留GROUP_CONCAT的值?
我想保留[运动,游戏]
答案 0 :(得分:1)
我想你想要返回包含“游戏”的新闻项目。如果是这样,这是正确的逻辑:
SELECT n.*, GROUP_CONCAT(c.name)
FROM news n JOIN
CatNews cn
ON n.id = cn.newsid JOIN
category c ON cn.cat_id = c.category_id
GROUP BY n.id
HAVING SUM(category_id = 'Games') > 0;