0

我有两个通过 id 相关的表。

图书:

book_id | book_name | year | publisher | slug

章节:

chapter_id | book_id | chapter_name

现在,当我查询数据库以查找与这样一本书相关的所有章节时:

SELECT book_name, chapter_name FROM ci_books, ci_chapters WHERE ci_books.book_id = ci_chapters.book_id AND slug = 'twelvers-dawn';

我得到:

**book_name | chapter_name**
twelvers  | Rising Sun
twelvers  | Slow Down
twelvers  | Masochist

我得到每章都重复的书名,我怎样才能阻止名称重复,以便只显示一次名称并显示所有章节?

4

2 回答 2

2

你可以GROUP_CONCAT()像这样使用:

SELECT book_name, GROUP_CONCAT(chapter_name) as ChapterNames 
FROM ci_books, ci_chapters 
WHERE ci_books.book_id = ci_chapters.book_id AND slug = 'twelvers-dawn'
GROUP BY book_name;

在此处查看资源

于 2013-11-11T01:11:42.223 回答
1

GROUP_CONCAT()与_GROUP_BY

SELECT book_name, GROUP_CONCAT(chapter_name) AS chapter_names
FROM ci_books, ci_chapters 
WHERE ci_books.book_id = ci_chapters.book_id AND slug = 'twelvers-dawn'
GROUP BY book_name;
于 2013-11-11T01:11:38.270 回答