K. *_* C 5 mysql sql sqlite combinations unique
我需要SQL代码来解决表组合问题,如下所述:
表旧数据:表旧
name version status lastupdate ID
A 0.1 on 6/8/2010 1
B 0.1 on 6/8/2010 2
C 0.1 on 6/8/2010 3
D 0.1 on 6/8/2010 4
E 0.1 on 6/8/2010 5
F 0.1 on 6/8/2010 6
G 0.1 on 6/8/2010 7
Run Code Online (Sandbox Code Playgroud)
表新数据:表新
name version status lastupdate ID
A 0.1 on 6/18/2010
#B entry deleted
C 0.3 on 6/18/2010 #version_updated
C1 0.1 on 6/18/2010 #new_added
D 0.1 on 6/18/2010
E 0.1 off 6/18/2010 #status_updated
F 0.1 on 6/18/2010
G 0.1 on 6/18/2010
H 0.1 on 6/18/2010 #new_added
H1 0.1 on 6/18/2010 #new_added
Run Code Online (Sandbox Code Playgroud)
新数据和旧日期的区别:
B条目已删除
C条目版本已更新
E条目状态已更新
C1/H/H1条目新添加
我想要的是始终保持旧数据表中的ID - 名称映射关系,无论以后数据如何更改,也就是名称始终具有绑定它的唯一ID号.
如果条目已更新,则更新数据,如果条目是新添加的,则插入表格,然后提供新分配的唯一ID.如果该条目已删除,请删除该条目,稍后不要重复使用该ID.
但是,我只能使用带有简单选择或更新语句的SQL,那么我可能很难编写这样的代码,那么我希望有专业知识的人可以给出方向,不需要有关SQL变体,标准sql代码的详细信息.样品就够了.
提前致谢!
RGS
KC
========我在这里列出了我的草稿sql,但不确定它是否有效,有些专业人士请评论,谢谢!
将表tmp创建为select*from old
更新tmp其中的名称(从新选择名称)
插入到tmp(名称版本状态lastupdate ID)set idvar = max(从tmp中选择max(id))+ 1 select*from(select new.name new.version new.status new.lastupdate new.ID from old,new where old.name <> new.name)
从tmp中删除(选择???)
您从未提及您正在使用什么 DBMS,但如果您使用 SQL Server,那么 SQLMERGE语句就是一个非常好的选择。请参阅:http://www.mssqltips.com/tip.asp?tip =1704
MERGE 语句基本上用作同一语句中的单独插入、更新和删除语句。您指定“源”记录集和“目标”表,以及两者之间的联接。然后,您可以指定当两个数据之间的记录匹配或不匹配时要发生的数据修改类型。MERGE 非常有用,特别是在加载数据仓库表时,这些表可能非常大,并且需要在行存在或不存在时采取特定操作。
例子:
MERGE Products AS TARGET
USING UpdatedProducts AS SOURCE
ON (TARGET.ProductID = SOURCE.ProductID)
--When records are matched, update
--the records if there is any change
WHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName
OR TARGET.Rate <> SOURCE.Rate THEN
UPDATE SET TARGET.ProductName = SOURCE.ProductName,
TARGET.Rate = SOURCE.Rate
--When no records are matched, insert
--the incoming records from source
--table to target table
WHEN NOT MATCHED BY TARGET THEN
INSERT (ProductID, ProductName, Rate)
VALUES (SOURCE.ProductID, SOURCE.ProductName, SOURCE.Rate)
--When there is a row that exists in target table and
--same record does not exist in source table
--then delete this record from target table
WHEN NOT MATCHED BY SOURCE THEN
DELETE
--$action specifies a column of type nvarchar(10)
--in the OUTPUT clause that returns one of three
--values for each row: 'INSERT', 'UPDATE', or 'DELETE',
--according to the action that was performed on that row
OUTPUT $action,
DELETED.ProductID AS TargetProductID,
DELETED.ProductName AS TargetProductName,
DELETED.Rate AS TargetRate,
INSERTED.ProductID AS SourceProductID,
INSERTED.ProductName AS SourceProductName,
INSERTED.Rate AS SourceRate;
SELECT @@ROWCOUNT;
GO
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
700 次 |
| 最近记录: |