例如,有阅读过以下数字书籍的用户:
History (1002,1424,2512,4625,1245)
Art (1592,6413,5030,5362)
Fantasy (5929,5920,1245,2152)
和
Users (a,b,c,d,e)
我想知道如何使用上述内容进行mysql查询。想知道有多少用户阅读过历史,艺术或幻想中的所有书籍因此,曾经阅读过《历史》,《艺术》或《幻想》中所有书籍的一位用户应该被收录。
SELECT
count(distinct Users) as User
FROM
table
WHERE
book_id in (1002,1424,2512,4625,1245) or
book_id in (1592,6413,5030,5362) or
book_id in (5929,5920,1245,2152)
并且以上查询似乎不包含所有书籍,因为我使用了'in'。
SELECT COUNT(user_id) AS userscount
FROM sourcetable
WHERE book_id in (1002,1424,2512,4625,1245,1592,6413,5030,5362,5929,5920,1245,2152)
GROUP BY user_id
HAVING SUM( book_id in (1002,1424,2512,4625,1245) ) = 5
OR SUM( book_id in (1592,6413,5030,5362) ) = 4
OR SUM( book_id in (5929,5920,1245,2152) ) = 4
查询假定(user_id, book_id)
被定义为唯一。