我正在尝试构建一个简单的数据库,用于跟踪用户位置属性的任何更改。每天我都会生成User,Date,Location的当前信息,并上传到sql server中的临时表。我试图找出正确的sql来查询新用户,修改过的用户和已删除的用户。
通过以下方式轻松查找新用户:
SELECT table1.UserGuid,table1.Location
FROM table1
WHERE table1.UserGuid NOT IN
(
SELECT DISTINCT table2.UserGuid
FROM table2
)
我遇到的问题是找到已修改的位置和已删除的用户。
对于修改后的用户,我试图返回用户,他们在数据库中的最后位置与每日临时数据库中的当前位置不匹配。这就是我所拥有的,但我不认为这是正确的:
SELECT table1.UserGuid,table1.Location
FROM table1
WHERE EXISTS
(
SELECT TOP 1 table2.UserGuid,table2.Location
FROM table2
WHERE (table2.UserGuid = table1.UserGuid) AND (table2.Location != table1.Location)
ORDER BY table2.Date DESC
)
对于已删除的用户,我正在尝试使用以下sql来识别主表中日常临时表中不存在且没有删除位置的任何用户。 (如果这会返回任何已删除的用户,那么我将它们添加到主表中,并将其删除,以便下次不再返回)
SELECT table2.UserGuid,table2.Location
FROM table2
WHERE table2.UserGuid NOT IN
(
SELECT UserGuid
FROM table1
)
AND table2.Location != 'deleted'
在我运行所有3个查询以查找添加,修改和删除后,我将它们与当前日期一起添加到主表并重复第二天。因此主表有3列(UserGuid,Date,Location),每天都会添加新行以及更改的信息。到目前为止,我的新用户sql是唯一可靠的工作。有更简单的方法吗?
答案 0 :(得分:0)
所以我认为这可以捕获您的所有要求。
Select
table1.*,
case when table2.userguid is null then 'INSERT'
when table1.userguid is null and table2.location != 'deleted' then 'DELETE'
when table1.location != table2.location then 'UPDATE'
from table1
full join (select max(date) as lastEntry, userGuid from Table2) lastRecords
inner join table2 on table2.date = lastRecords.lastEntry and table2.userGuid = lastRecords.userGuid
on lastRecords.userguid = table1.userguid
答案 1 :(得分:0)
对于第二个查询,请尝试:
SELECT table1.UserGuid,table1.Location
FROM table1
WHERE table1.UserGuid IN
(
SELECT table2.UserGuid
FROM table2
WHERE table2.UserGuid = table2.UserGuid AND table2.Location <> table2.Location
)
答案 2 :(得分:0)
我倾向于使用EXISTS进行这类检查
--INSERTS
SELECT table1.UserGuid,table1.Location
FROM table1
WHERE NOT EXISTS (SELECT 1 FROM table2 WHERE table2.UserGuid = table1.UserGuid)
UNION ALL
--UPDATES
SELECT table1.UserGuid,table1.Location
FROM table1
WHERE EXISTS
(
SELECT 1 FROM table2
WHERE table2.UserGuid = table1.UserGuid
AND ISNULL(table2.Location,'') <> ISNULL(table1.Location,'')
)
UNION ALL
--DELETES
SELECT table2.UserGuid,table2.Location
FROM table2
WHERE NOT EXISTS (SELECT 1 FROM table1 WHERE table2.UserGuid = table1.UserGuid)
如果您的位置可能为空,我会包含ISNULL检查;如果那是不可能的话,就不需要它们。