2选择1个插入语句

时间:2014-01-12 06:21:31

标签: sql select insert inner-join

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

首先我有一张名为库存,卖出和忠诚卡的表。表库存包括列名称,类别,品牌,价格......而忠诚卡的列名称为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 

1 个答案:

答案 0 :(得分:0)

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

这会导致数据无效。

需要做什么 -

  

第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')

虽然您应该使用连接替换子查询,以便正确更新所有行。