如何在查询的一列中放置多值属性?

时间:2012-08-23 15:45:15

标签: mysql sql database

例如,在我的数据库中,我有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 |
    +----------------------------------+

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

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

  

SELECT @temp:= @ temp + 1 AS ID,Book_Title,Tags FROM(SELECT title as   Book_Title,GROUP_CONCAT(tag_name)AS标签FROM(SELECT BOOKS.title,   TAGS.tag_name FROM(car: [word] house: [word] blog: [word] 加入书籍BOOKS.id =   BOOK_TAGS.book_id)加入TAGS.id = BOOK_TAGS.tag_id)tbl GROUP   BY title)AS tbl CROSS JOIN(SELECT @temp:= 0)AS dummy