1

我的一个 SQL 请求确实存在阻塞问题。我的问题如下:我有一个包含一些用户及其姓名、地址、电话号码的第一个表(一个临时表)......我有一个包含有关某些命令的信息的第二个表(一个“真实”表) . 命令与用户相关,但有点复杂。为了更清楚起见,这里是我的表格定义的示例:

USER
ID          char(8)
LastName    nvarchar(30)
FirstName   nvarchar(30)
PostCode    nvarchar(10)
PhoneNumber nvarchar(20)
HomeAdress  nvarchar(20)

COMMAND
ID            char(6)
CMD_FirstName nvarchar(20)
CMD_LastName  nvarchar(20)
CMD_PostCode  nvarchar(10)
ID_User       char(8)

这两个表在逻辑上是相关的,但在实践中却没有……在COMMAND表中,通常缺少“ID_User”字段。我的 SQL resquest 的目的是通过填充 ID_User 字段在所有命令和相应用户之间建立关联。对于 ID_User 为空或为空的每个命令,我想通过匹配字段姓氏、名字和邮政编码来检索用户。如果这个匹配是严格的(在 USER 表中没有 doublon,这很重要),我可以填写 ID_User 字段。

你能帮我解决这个大而复杂的请求吗?提前,谢谢!

PS:我使用的是 Microsoft SQL Server 2008 R2

4

2 回答 2

4
update c
set id_user = u.ID
from [user] u
join [command] c on c.cmd_firstname = u.firstname
                and c.cmd_lastname = u.lastname
                and c.cmd_postcode = u.postcode;

要排除匹配多个 的 firstname/lastname/postcode 组合user,您可以预先聚合user表并将其过滤掉。

update c
set id_user = u.ID
from [command] c
join (select firstname, lastname, postcode, min(ID) ID
        from [user]
       group by firstname, lastname, postcode
      having count(*) = 1) u
   on c.cmd_firstname = u.firstname
  and c.cmd_lastname = u.lastname
  and c.cmd_postcode = u.postcode;
于 2013-04-23T10:18:14.340 回答
1

您需要确保 [USER] 和 [COMMAND] 都不包含您要用于映射它们的字段的重复记录。这包含相关查询,对于大型表可能不是很有效。

update [command]
set ID_User = u.id
from [USER] u
join COMMAND c
    on u.LastName=c.CMD_LastName
    and u.FirstName = c.CMD_FirstName
    and u.PostCode = c.CMD_PostCode
where 1=1
    and not exists (
        select 
            LastName, FirstName, PostCode
        from [user]
        where 1=1
            and LastName=u.LastName
            and FirstName=u.FirstName
            and PostCode=u.PostCode
        group by 
            LastName, FirstName, PostCode
        having count(*)>1 
    )
    and not exists (
        select 
            CMD_LastName, CMD_FirstName, CMD_PostCode
        from COMMAND
        where 1=1
            and CMD_FirstName=c.CMD_FirstName
            and CMD_LastName=c.CMD_LastName
            and CMD_PostCode=c.CMD_PostCode
        group by 
            CMD_LastName, CMD_FirstName, CMD_PostCode
        having count(*)>1 
    )
于 2013-04-23T10:24:41.127 回答