SQL多对多关系:在关系表中创建N条随机记录
有树表:SQL多对多关系:在关系表中创建N条随机记录,sql,sql-server,many-to-many,Sql,Sql Server,Many To Many,有树表: Table1 ------------------ | Id | CreatedBy | ------------------ Table2 ------------------ | Id | CreatedBy | ------------------ Table3 (table to store relations between Table1 and Table2) ----------------------- | table1Id | table2Id | -------
Table1
------------------
| Id | CreatedBy |
------------------
Table2
------------------
| Id | CreatedBy |
------------------
Table3 (table to store relations between Table1 and Table2)
-----------------------
| table1Id | table2Id |
-----------------------
我在表1和表2中有许多不同创建者的记录。我需要的是为同一个创建者在表1中的所有记录和表2中的N个随机记录之间创建关系
我已经尝试过的:
创建带有内部联接的select,该联接将创建关系记录
这里的问题是,子查询可以返回由其他创建者创建的前10条记录,在t1.CreateBy=t2.CreatedBy之后,我们将得到空结果
编写此查询时不使用join select语句,但没有成功。
这就是解决方案:
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
为什么只想创建部分数据?这是一个非常奇怪的要求。也许是这样的
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
你能更好地解释一下你想做什么吗?您正在从表2中提取随机记录以匹配表1中的记录。。。为什么?通常,当表之间存在多对多关系时,您希望创建一个桥接实体以将该关系更改为多对1。您只是在生成一些测试数据,以便处理一些数据吗?我希望如此,否则这对我来说没有多大意义。@DanK:我在表1和表2中有单独的实体,但用户可以用多种方式将它们关联起来。出于测试目的,我在表1和表2中生成了实体,现在我想在它们之间创建关系。所以我想为表1中的每个实体和表2中的几个随机实体创建关系。每个用户有N条记录还是总共有N条记录?我猜用户是基于这个。。。结果可能是N或
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