从联接中获取常用记录

时间:2019-02-20 09:55:32

标签: tsql join

我有2个表-用户和用户手册:

USERID  USERNAME  (USERS)
 --------  -------
 1         User1
 2         User2
 3         User3
 .         UserX

ID   USERID    BOOKID (USERBOOKS)
---  --------  -------
 1     1         1
 2     2         1
 3     3         1
 4     2         2
 5     2         2
 .   userx      bookx

在此示例中,我希望获得通用记录(每个用户阅读的通用阅读书籍),以使阅读书籍1的用户受益,但是书籍ID总是会变化的

2 个答案:

答案 0 :(得分:0)

除非我缺少明显的内容,否则您正在寻找exists

SELECT UserId, UserName  
FROM Users
WHERE EXISTS
(
    SELECT 1
    FROM UserBooks
    WHERE UserBooks.UserId = USERS.UserId
    AND BookId = 1
)

这将返回UserBooks中具有bookId 1的相应记录的所有用户。

答案 1 :(得分:0)

尝试一下:

DECLARE @BOOK INT = 2;

SELECT UB.BOOKID,U.USERNAME,COUNT(*) AS TIMES 
FROM @USERBOOKS UB
INNER JOIN @USERS U ON UB.USERID = U.USERID
WHERE UB.BOOKID = @BOOK
GROUP BY BOOKID,U.USERNAME
ORDER BY 1,2 
;

请注意,用户2两次使用了图书ID 2