我有两个通过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
我得到了每一章重复的书的名称,我怎样才能阻止名称重复,以便只显示一次名称并显示所有章节?
答案 0 :(得分: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;
请参阅资源here
答案 1 :(得分:1)
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;