English 中文(简体)
SQL:在含有外国密钥的表格中插入来自另一个表格的数据
原标题:SQL: Insert data from another table in a table that contains foreign keys

在一个 SQL 数据中

我有一张表格用户

 Id   Name   Age    AddressId
----+------+------+-----------

地址标识是表格名称地址的外国密钥

地址表:

 Id   Country   State  City   ZipCode
----+---------+------+------+---------

这是一个一对一的关系:每个用户有一个地址,每个地址只有一个用户

我有一张新桌子叫新用户

Id   Name  
----+------

它只有日期和名称。

我想做的是:

写入一个脚本, 将所有从 UnewUSers 表格中输入到用户表格中的所有记录插入到用户表格中 。

  • I want The Age to be default 20 for all new users
  • And for each new user inserted I need to create a new Address record for him
  • the new Address record will have all it s values (country, city, state, zipcode) equal to "abcd" except the Id which will be used to set the foreign key AddressId for the new user)

我怎样才能做到呢?

我尝试了以下方法:

INSERT INTO Users(Name, Age)
Values((SELECT Name FROM NewUsers),20)

但我不知道如何为插入的每个用户创建新的地址记录, 并相应指定外国密钥 。

谢谢你的帮忙

最佳回答

一种方法是两种查询,其组成如下:

INSERT INTO Addresses (Country, State, City, ZipCode)
SELECT  abcd ,  abcd ,  abcd ,  abcd  FROM NewUsers

INSERT INTO Users (Name, Age, AddressId)
SELECT Name, 20, ?? FROM NewUsers

Edit: 将用户与地址连接起来的一个简单方式是临时设置国家用户名。 然后您将有一个链接来确定地址ID。 一旦用户表被配置并正确连接, 您可以将国家放回默认值 abcd :

insert addresses (country, state, city, zipcode)
select name,  abcd ,  abcd ,  abcd  from newusers;

insert users (name, age, addressid)
select u.name, 20, a.id from newusers u
join addresses a on a.country = u.name;

update a
set a.country =  abcd 
from addresses a join newusers u on a.country = u.name;

网站:http://www.sqlfiddle.com/#!3/1f09b/8" rel="noreferrer" >http://www.sqlfiddle.com/#!3/1f09b/8

如果您想要在多个插入可以同时发生的情况下保证交易的一致性,或者如果您想要允许重复名称,等等。但是,根据您给出的范例和迄今为止的详细情况,这种方法应该发挥作用。

问题回答

这是有点黑,但做你想要做的 在两个语句中 - 假设用户不会拥有名字 abcd 或输入他们国家的名称, 并且你清洗了新用户表格 。

INSERT dbo.Addresses(Country, State, City, ZipCode)
OUTPUT inserted.Country, 20, inserted.id
INTO dbo.Users
SELECT Name,  abcd ,  abcd ,  abcd 
FROM dbo.NewUsers;

UPDATE a SET Country =  abcd 
FROM dbo.Addresses AS a
INNER JOIN dbo.NewUsers AS nu
ON a.Country = nu.Name;

您必须用冒名密钥写入用户和地址表格时使用的光标

DECLARE @AddressID INT,
        @ID INT,
        @Name NVARCHAR(50)

DECLARE UserCursor CURSOR FOR
SELECT ID, NAME
FROM NewUsers
OPEN UserCursor

FETCH NEXT FROM UserCursor INTO @ID, @Name
WHILE @@FETCH_STATUS =0 BEGIN
    INSERT INTO Addresses(Country, State, City, ZipCode)
    VALUES ( abcd ,  abcd ,  abcd ,  abcd )

    SET @AddressID = SCOPE_IDENTITY()

    INSERT INTO Users(Name, Age, AddressID)
    VALUES (@Name, 20, @AddressID)
    FETCH NEXT FROM UserCursor INTO @ID, @Name
END
CLOSE UserCursor
DEALLOCATE UserCursor

假设您可以任意设置地址标识...

INSERT Addresses
(
    Id,
    Country,
    State,
    City,
    ZipCode
)
SELECT
    Id,
     abcd ,
     abcd ,
     abcd ,
     abcd 
FROM NEWUsers

INSERT Users
(
    Id,
    Name,
    Age,
    AddressId
)
SELECT
    Id,
    Name,
    20,
    Id
FROM NEWUsers

如果地址 Id 是身份栏, 您可以先暂时禁用身份 。 请查看 < a href=" http:// msdn. microsoft. com/ en- us/library/ ms188059%28v=sql. 100%29. aspx" rel = “ nofollow' >SETIDIDENTION_INSERT 的信息和示例 。

坦率地说,答案是,您不想做你想做的事。如果用户有一个而且只有一个地址,正如您所说的,那么您应该只有一个包含地址字段的表格(用户)。对您的数据进行适当建模,可以使问题从本质上消失。





相关问题
what is wrong with this mysql code

$db_user="root"; $db_host="localhost"; $db_password="root"; $db_name = "fayer"; $conn = mysqli_connect($db_host,$db_user,$db_password,$db_name) or die ("couldn t connect to server"); // perform query ...

Users asking for denormalized database

I am in the early stages of developing a database-driven system and the largest part of the system revolves around an inheritance type of relationship. There is a parent entity with about 10 columns ...

Easiest way to deal with sample data in Java web apps?

I m writing a Java web app in my free time to learn more about development. I m using the Stripes framework and eventually intend to use hibernate and MySQL For the moment, whilst creating the pages ...

join across databases with nhibernate

I am trying to join two tables that reside in two different databases. Every time, I try to join I get the following error: An association from the table xxx refers to an unmapped class. If the ...

How can I know if such value exists in database? (ADO.NET)

For example, I have a table, and there is a column named Tags . I want to know if value programming exists in this column. How can I do this in ADO.NET? I did this: OleDbCommand cmd = new ...

Convert date to string upon saving a doctrine record

I m trying to migrate one of my PHP projects to Doctrine. I ve never used it before so there are a few things I don t understand. In my current code, I have a class similar to this: class ...

热门标签