不存在时插入数据

时间:2016-01-15 10:41:10

标签: sql sql-server tsql

我有那张图。两个表的UserId相同(将其作为外键)。 如何在UserId表中不存在UserAdditioStamp,然后在UserAdditioStamp表中插入这些数据。

enter image description here

SELECT 
    min(ev.UserId) as UserId, ev.Value, 
    min(uas.UserId) as AdditionUserId, 
    max(uas.[TimeStamp]) as AdditionTimestamp, 
    count(ev.UserId) as [Registrations]
FROM 
    EventLog ev
LEFT JOIN
    UserAdditionStamp uas ON ev.UserId = uas.UserId
WHERE 
    uas.UserId IS NULL
    AND EventTypeId = 3 
    AND Value IS NOT NULL
GROUP BY
    ev.Value
ORDER BY
    UserId

我正在尝试选择但是它给出了关于注册计数的错误结果(UserId = 10应该注册2次,13等注册2)。

UserId AdditionUserId AdditionTimestamp [Registrations]
3       NULL                NULL            1
10      NULL                NULL            1
10      NULL                NULL            1
13      NULL                NULL            1
13      NULL                NULL            1

然后我想在UserAdditioStamp表中插入这些数据。怎么可能?

3 个答案:

答案 0 :(得分:1)

INSERT INTO UserAdditionStamp 
SELECT e.UserId, e.TimeStamp 
FROM EventLog e 
WHERE NOT EXISTS (SELECT UserId FROM UserAdditionStamp WHERE UserId = e.UserId)

OR

INSERT INTO UserAdditionStamp 
SELECT e.UserId, e.TimeStamp 
FROM EventLog e 
WHERE e.UserId NOT IN (SELECT UserId FROM UserAdditionStamp)

答案 1 :(得分:0)

如果我理解正确:

insert into UserAdditionStamp ( UserId, TimeStamp )
select UserId, TimeStamp 
from EventLog 
where (userId not in ( select UserId from UserAdditionStamp ))

答案 2 :(得分:0)

我不明白你的问题。您谈到插入数据然后通过选择问题谈论一个组。如果问题的核心是

  

如果UserAdditionStamp中不存在UserId,我想将EventId和TimeStamp从EventLog插入UserAdditionStamp表

然后一种可读的方式是用户merge,一种方法:

; WITH E as 
( select  e.UserId, MAX( e.TimeStamp  ) as TimeStamp
FROM EventLog e
GROUP BY  e.UserId
)
MERGE UserAdditionStamp AS TARGET
USING E as SOURCE
WHEN NOT MATCHED BY TARGET THEN
    INSERT (UserId, TimeStamp )
    VALUES (SOURCE.UserId, SOURCE.TimeStamp)
END;

但根据MS performance tip

  

性能提示:当两个表具有匹配特征的复杂混合时,为MERGE语句描述的条件行为效果最佳。例如,如果行不存在则插入行,或者如果行匹配则更新行。当简单地基于另一个表的行更新一个表时,可以使用基本的INSERT,UPDATE和DELETE语句实现改进的性能和可伸缩性。

使用简单的插件,您将获得更多性能:

INSERT UserAdditionStamp (UserId, TimeStamp )
SELECT e.UserId, MAX( e.TimeStamp  ) as TimeStamp
FROM EventLog e 
WHERE NOT EXISTS (SELECT 1 
                  FROM UserAdditionStamp A2
                  WHERE A2.UserId = e.UserId)
GROUP BY  e.UserId
;