如何使用WHERE语句获得结果的完整GROUP_CONCAT列表?

时间:2012-05-07 21:45:12

标签: mysql

这是我的数据库结构示例..

uid  email            name
-------------------------------
1    john@gmail.com   John
2    peter@gmail.com  Peter
3    colin@gmail.com  Colin
书表

book_id  book_name
-------------------
1        PHP
2        MySQL
3        Javascripts
4        CSS

历史表

history_uid  history_bookid
---------------------------
1            1
1            2
1            3
2            1
2            3
3            3

当前声明包括history.history_bookid

上的多选查询
SELECT users.uid,
       users.email,
       users.`name`,
       history.history_uid,
       history.history_bookid,
       GROUP_CONCAT(history.history_bookid) AS BookID,
       GROUP_CONCAT(book_name)              AS bookTitles
FROM   users
       INNER JOIN history
         ON users.uid = history.history_uid
       INNER JOIN book
         ON history.history_bookid = book.book_id
WHERE  history.history_bookid = 1
        OR history.history_bookid = 3
GROUP  BY users.uid  

结果

uid email            name   history_uid  history_bookid  BookID   bookTitles
---------------------------------------------------------------------------------
1   john@gmail.com   John   1            3               3,1      Javascripts,PHP
2   peter@gmail.com  Peter  2            1               1,3      PHP,Javascripts
3   colin@gmail.com  Colin  3            3               3        Javascripts

问题:

uid = 1如何阅读完整的图书清单?我想要的示例输出包括history table

中的所有书籍
uid email            name   history_uid  history_bookid  BookID   bookTitles
---------------------------------------------------------------------------------
1   john@gmail.com   John   1            3               1,2,3    PHP,MySQL,Javascripts
2   peter@gmail.com  Peter  2            1               1,3      PHP,Javascripts
3   colin@gmail.com  Colin  3            3               3        Javascripts

2 个答案:

答案 0 :(得分:1)

你是说你想要标题以及书籍ID?

在您的字段列表中添加GROUP_CONCAT(book_name) AS bookTitles

答案 1 :(得分:1)

  

如何通过uid = 1阅读完整的图书清单?

将其添加为WHERE子句的过滤器选项:

WHERE history.history_bookid IN (1,3) OR users.uid = 1