如何在没有公共密钥的情况下加入 2 tables 并随机生成第二行 table
How to join 2 tables without common key and randomly generate rows of second table
我有 2 个表.. [用户] 和 [问题]
用户 Table 有..
UserId Name
-- ----
1 Bob
2 Ang
3 Bill
问题 Table 有..
QuestId Description CategoryId
------- ---------- --------
0 Question0 1
1 Question1 1
2 Question2 1
3 Question3 1
4 Question4 1
5 Question5 1
6 Question6 1
7 Question7 1
8 Question9 1
9 Question9 1
10 Question10 2
现在,我想要的是 select 每个 [User] 5 个随机问题。
我试过这个查询..
SELECT [User].UserId,Name, QuestId, Description from Users OUTER APPLY
(SELECT TOP 5 QuestId, Description FROM Question WHERE CategoryId=1 ORDER BY NEWID(),
Question.Id) RandomQuestions
结果是这样的..
UserId Name QuestId Description
------ ---- ------- -----------
1 Bob 2 Question2
1 Bob 3 Question3
1 Bob 6 Question6
1 Bob 8 Question8
1 Bob 9 Question9
2 Ang 2 Question2
2 Ang 3 Question3
2 Ang 6 Question6
2 Ang 8 Question8
2 Ang 9 Question9
3 Bill 2 Question2
3 Bill 3 Question3
3 Bill 6 Question6
3 Bill 8 Question8
3 Bill 9 Question9
问题在于,QuestId 是随机生成的,但如果您注意到,每个用户都有相同的随机生成问题。我希望每个用户都有不同的随机问题集。
你需要这样随机QuestionID
WHERE QuestId = (ABS(CHECKSUM(NEWID()) % 10)) + 1
使用这个:
SELECT UserId,Name,QuestId, Description
FROM Users a
CROSS apply (
SELECT TOP 5 Row_number() OVER(ORDER BY (SELECT NULL)) AS RowNo, *
FROM (SELECT TOP 5 QuestId, Description
FROM Question b
WHERE a.UserId = a.UserId
ORDER BY Newid()) S
) cs
我有 2 个表.. [用户] 和 [问题]
用户 Table 有..
UserId Name
-- ----
1 Bob
2 Ang
3 Bill
问题 Table 有..
QuestId Description CategoryId
------- ---------- --------
0 Question0 1
1 Question1 1
2 Question2 1
3 Question3 1
4 Question4 1
5 Question5 1
6 Question6 1
7 Question7 1
8 Question9 1
9 Question9 1
10 Question10 2
现在,我想要的是 select 每个 [User] 5 个随机问题。
我试过这个查询..
SELECT [User].UserId,Name, QuestId, Description from Users OUTER APPLY
(SELECT TOP 5 QuestId, Description FROM Question WHERE CategoryId=1 ORDER BY NEWID(),
Question.Id) RandomQuestions
结果是这样的..
UserId Name QuestId Description
------ ---- ------- -----------
1 Bob 2 Question2
1 Bob 3 Question3
1 Bob 6 Question6
1 Bob 8 Question8
1 Bob 9 Question9
2 Ang 2 Question2
2 Ang 3 Question3
2 Ang 6 Question6
2 Ang 8 Question8
2 Ang 9 Question9
3 Bill 2 Question2
3 Bill 3 Question3
3 Bill 6 Question6
3 Bill 8 Question8
3 Bill 9 Question9
问题在于,QuestId 是随机生成的,但如果您注意到,每个用户都有相同的随机生成问题。我希望每个用户都有不同的随机问题集。
你需要这样随机QuestionID
WHERE QuestId = (ABS(CHECKSUM(NEWID()) % 10)) + 1
使用这个:
SELECT UserId,Name,QuestId, Description
FROM Users a
CROSS apply (
SELECT TOP 5 Row_number() OVER(ORDER BY (SELECT NULL)) AS RowNo, *
FROM (SELECT TOP 5 QuestId, Description
FROM Question b
WHERE a.UserId = a.UserId
ORDER BY Newid()) S
) cs