有树表:
Table1
------------------
| Id | CreatedBy |
------------------
Table2
------------------
| Id | CreatedBy |
------------------
Table3 (table to store relations between Table1 and Table2)
-----------------------
| table1Id | table2Id |
-----------------------
我在表1和表2中有很多不同创作者的记录。我需要的是在表1中的所有记录与表2中的N个随机记录之间创建关系(当然对于同一个创建者)。
我已经尝试过了:
INSERT INTO Table3 SELECT t1.Id, t2.Id FROM Table1 t1 INNER JOIN (SELECT TOP(10) Id, CreatedBy FROM Table2 ORDER BY NEWID()) AS t2 ON t1.CreateBy = t2.CreatedBy
这里的问题是子查询可以返回由其他创建者创建的前10条记录,并且在ON t1.CreateBy = t2.CreatedBy之后我们将得到空结果。
答案 0 :(得分:1)
为什么您只想创建部分数据?这是一个非常奇怪的要求。这样的事可能吗?
with MyCTE as
(
SELECT t1.Id as ID1, t2.Id as ID2, ROW_NUMBER() over (partition by t1.CreateBy order by (select newid())) as RowNum
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.CreateBy = t2.CreatedBy
)
insert Table3
select ID1, ID2
from MyCTE
where RowNum <= 10
答案 1 :(得分:0)
这是解决方案:
Declare @Query Nvarchar(Max)
Declare @Num int=10
Set @Query='
Select a.Id,b.Id
From Table1 a
Inner join (
Select top '+ltrim(Rtrim(Str(@Num)))+' t.Id,t.CreatedBy
From Table2 t order by newid()) as b
On (a.CreatedBy=b.CreatedBy)'
Exec sp_executesql @Query