我有3个表:项目,类别和 projects_categories 。
我想获取项目名称,描述和类别,但每个项目可以有多个类别,因此我使用下一个查询获取重复内容:
SELECT projects.name, projects.description, categories.name
FROM projects
JOIN projects_categories ON projects.project_id = projects_categories.project_id
JOIN categories ON projects_categories.category_id = categories.category_id
WHERE projects.project_id = ?
我得到了这个:
++ name +++ ++ description ++ ++ name (category) ++
project1 bla bla bla film
project1 bla bla bla music
你可以看到我得到两行而不是一行
答案 0 :(得分:2)
Group_concat是您要查找的标记:
SELECT projects.name,
projects.description,
group_concat(categories.name SEPARATOR ' ') as category_name
FROM projects
JOIN projects_categories
ON projects.project_id = projects_categories.project_id
JOIN categories
ON projects_categories.category_id = categories.category_id
WHERE projects.project_id = ?
group by projects.name, projects.description
答案 1 :(得分:1)
您可以使用GROUP_CONCAT组合类别并返回一行。
SELECT projects.name, projects.description, GROUP_CONCAT(categories.name)
FROM projects
JOIN projects_categories ON projects.project_id = projects_categories.project_id
JOIN categories ON projects_categories.category_id = categories.category_id
WHERE projects.project_id = ?
GROUP BY projects.name, projects.description