2

例如,在我的数据库中,我有 3 个表,

  • 用于存储书籍数据的 Books 表
  • 用于存储标签数据的标签表
  • 以及用于存储关于具有多个标签的书的信息的链接表(Book_Tags 表)。

如下图所示...(箭头上方的“M”表示关系的多方面)

    BOOKS                    BOOK_TAGS                      TAGS
    +----+---------+         +---------+----------+         +----+---------------+
    |ID  |  Title  |         |Book_Id  |  Tags_Id |         |ID  |  Tag_Name     |
    +----+---------+         +---------+----------+         +----+---------------+ 
    |1   |  Book_1 | 1    M  |1        | 1        | M     1 |1   |  Tag_Name_1   |
    |1   |  Book_1 |<--------|1        | 2        |-------->|2   |  Tag_Name_2   |
    +----+---------+         |1        | 3        |         |3   |  Tag_Name_3   |
                             |2        | 1        |         +----+---------------+ 
                             |2        | 3        |         
                             +---------+----------+         

我的问题是,我如何查询我的数据库,以便得到类似的结果

    +---------------------------------------------------------+
    |ID  |  Book_Title  |   Tags                              |
    +---------------------------------------------------------+
    |1   |  Book_1      |   Tag_Name_1, Tag_Name_2, Tag_Name_3|
    |2   |  Book_2      |   Tag_Name_1, Tag_Name_3            |
    +---------------------------------------------------------+

而不是像

    +----------------------------------+
    |ID  |  Book_Title  |   Tags       |
    +----------------------------------+
    |1   |  Book_1      |   Tag_Name_1 |
    |2   |  Book_1      |   Tag_Name_2 |
    |3   |  Book_1      |   Tag_Name_3 |
    |4   |  Book_2      |   Tag_Name_1 |
    |5   |  Book_2      |   Tag_Name_3 |
    +----------------------------------+
4

3 回答 3

3

您可以使用 GROUP BY 子句来聚合结果并进行字符串追加。所以像:

SELECT bk.Book_Title, GROUP_CONCAT(bt.Book_Id SEPARATOR ', ') FROM BOOK_TAGS bt
JOIN BOOKS bk ON bk.ID = bt.Book_Id
JOIN TAGS t ON t.ID = bt.Tags_Id
GROUP BY bt.Book_Id
于 2012-08-23T15:51:59.410 回答
1
    SELECT b.book_title, tmp.tag_name from books b
    INNER JOIN (
SELECT bt.book_id as book_id , group_concat(t.tag_name) as tag_name FROM book_tags bt 
    INNER JOIN tags t ON t.tag_id =  bt.tags_id
) tmp
    ON tmp.book_id = b.id
于 2012-08-23T15:53:02.530 回答
0

下面是带有自动增量 ID 的 sql 查询。

SELECT @temp:=@temp+1 AS ID, Book_Title, Tags FROM (SELECT title as Book_Title, GROUP_CONCAT(tag_name) AS Tags FROM (SELECT BOOKS.title, TAGS.tag_name FROM ( book_tagsJOIN BOOKS ON BOOKS.id = BOOK_TAGS.book_id ) 在 TAGS.id=BOOK_TAGS.tag_id 上加入标签) tbl GROUP BY 标题) 作为 tbl 交叉连接 (SELECT @temp:=0) 作为虚拟

于 2015-10-24T10:34:26.217 回答