【问题标题】:Inserting mock data into an associative table in SQL with a composite key使用复合键将模拟数据插入到 SQL 中的关联表中
【发布时间】:2016-11-23 00:12:29
【问题描述】:

潜伏已久的第一次海报!

我正在开发一个 SQL 数据库以配合我的 Web 应用程序使用。我有两个关联表来连接多对多关系。我正在使用 Mockaroo 根据需要为我的表生成模拟数据,然后我来到我的关联表。

我现在的架构如下所示:

CREATE TABLE Test (
dirtId INT NOT NULL,
lightId INT NOT NULL,
PRIMARY KEY (dirtId, lightId),
FOREIGN KEY (dirtId) REFERENCES Dirts (id),
FOREIGN KEY (lightId) REFERENCES Lights (id)
);

我正在尝试弄清楚如何为我的主键生成模拟数据,甚至在使用这样的复合键时如何生成 INSERT 语句的格式。

对于我的外键,我没有看到仅在另一个表中的值中使用随机整数填充它的问题,但我不确定语法或使用 mockaroo 完成此操作的方式。提前致谢!

【问题讨论】:

    标签: sql database xampp primary-key composite-key


    【解决方案1】:

    使用 CTE 的简单示例。

    ;with tbl as (
    select 1 id
    union all
    select id+1
    from tbl where id<10
    )
    --insert myTable
    select t1.id dirtId, t2.id lightId
    from tbl t1 cross join tbl t2
    

    如果您的 DBMS 不支持 CTE,那么另一种解决方案。

    create table #tbl (id int)
    declare @id int = 1
    while @id < 11
    begin
    insert #tbl values(@id)
    set @id += 1
    end
    --insert myTable
    select t1.id dirtId, t2.id lightId
    from #tbl t1 cross join #tbl t2
    --drop table #tbl
    

    或者,如果您在 DirtsLights 中有某些内容,则以相同的方式使用它们。

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 2022-08-20
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多