【问题标题】:2 Select statements in 1 insert2 在 1 个插入中选择语句
【发布时间】:2014-01-31 01:19:50
【问题描述】:
Insert into sold(invId, cusId, LCnumfk, Name, Category, Brand, Price, ExDate, Tags, Quantity, Barcode)   
Select I.Id, L.Id, L.LCnum, I.Name, I.Category, I.Brand, I.Price, I.ExDate, I.Tags, I.Quantity, I.Barcode from inventory as I   
INNER JOIN sold as S on I.Id = S.invId INNER JOIN loyaltycard as L on S.CusId = L.Id where I.Barcode = 356554745

首先,我有一个名为 inventory、sold 和会员卡的表。表库存由列名称、类别、品牌、价格...组成,忠诚卡的列名称为 id 和 LCnum。我希望将所有这些值插入到已售表中。我该怎么做?

我尝试了这段代码并尝试了运气,但仍然没有..

Insert into sold(invID, Name, Category, Brand, Price, ExDate, Tags, Quantity, Barcode)  
Select Id, Name, Category, Brand, Price, ExDate, Tags, Quantity, Barcode from inventory  
where Barcode = '3565547456644' 
Insert into sold(CusId, LCnumfk)   
Select Id, LCnum from loyaltycard where LCnum = '347'

这是数据库的结构:

inventory(Id int , Name varchar(255), Category varchar(255), Brand varchar(255), Price int, ExDate date, Tags varchar(255), Quantity int, Barcode varchar(255))

sold(invId int, CusId int, LCnumfk int,Name varchar(255), Category varchar(255), Brand varchar(255), Price int, ExDate date, Tags varchar(255), Quantity int, Barcode varchar(255) ) 

loyaltycard(Id int, LCnum int)

sold foreign key LCnumfk has a constraint to loyaltycard LCnum

sold invId is a foreign key and has a constraint to inventory Id 

【问题讨论】:

    标签: sql select insert inner-join


    【解决方案1】:

    如果您执行 2 次插入 - 第一组的 CustId 和 LCnumfk 将为 NULL。第二个插入语句会将除 CustId 和 LCnumfk 之外的所有其他字段填充为 NULL。

    这会导致无效数据。

    需要做什么-

    第 1 步 - 插入数据

    Insert into sold(invID, Name, Category, Brand, Price, ExDate, Tags, Quantity, Barcode)  
    Select Id, Name, Category, Brand, Price, ExDate, Tags, Quantity, Barcode from inventory  
    where Barcode = '3565547456644' 
    

    第 2 步 - 更新第 1 步中插入的“已售”表的行

    Update sold
    SET CusId = (Select Id from loyaltycard where LCnum = '347'),
    LCnumfk = (Select LCnum from loyaltycard where LCnum = '347')
    

    尽管您应该用连接替换子查询以正确更新所有行。

    【讨论】:

    • 在插入查询中有错误。消息 515,级别 16,状态 2,第 1 行无法将值 NULL 插入列“CusId”,表“sys.dbo.sold”;列不允许空值。插入失败。该语句已终止。当我尝试查询并检查表时出现此错误,它仅更新了已售表的 CusId 和 LCnumfk。它不插入值
    • 答案中的插入查询与问题中的查询相同。您收到此错误的原因是因为它违反了您的 Sold 表的约束
    • 你能分享Sold表和inventory表的结构吗?这两张表之间有什么关系吗?
    • 是的。已售出的 invId 是外键,对库存 Id 有约束
    • 请分享-inventory,sold,loyaltycard的表结构
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多