我有两张桌子
tbl_contact
contactID identity(1,1) not null,
contactname varchar(100)
tbl_l_contact_fund
l_contact_fund_id identity(1,1) not null,
contactID int FK to tbl_contact (contactID),
fundID int
我的 tbl_contact 表中有重复的联系人姓名,他们已经链接到 tbl_l_contact_fund
我想查询将所有重复联系人名称的关联从一个ID移到tbl_contact中的其他ID,并删除重复的联系人。我可以获得删除dup的最佳方法吗?谢谢!
例如:输入
tbl_contact
contactID ContactName
1 Manoj
2 Manoj
3 Rahul
4 Ajay
5 Rahul
6 Ajay
tbl_l_contact_fund
l_contact_fund_id contactID fundID
1 1 1
2 2 2
3 1 3
4 4 1
5 6 2
6 5 1
最终输出:
tbl_contact
contactID ContactName
1 Manoj
3 Rahul
4 Ajay
tbl_l_contact_fund
l_contact_fund_id contactID fundID
1 1 1
2 1 2
3 1 3
4 4 1
5 4 2
6 5 1
答案 0 :(得分:1)
他的遗嘱将使用CTE
WITH crows AS (
SELECT MIN(contactID) contactID, ContactName
FROM tbl_contact
GROUP BY ContactName
)
UPDATE tbl_l_contact_fund
SET contactID = (SELECT ContactID
FROM crows cr
WHERE ContactName in
(SELECT ContactName
FROM tbl_contact
WHERE ContactID = a.contactID))
FROM tbl_l_contact_fund a
GO
DELETE tbl_contact WHERE ContactID NOT IN (SELECT MIN(contactID) contactID
FROM tbl_contact GROUP BY ContactName)
或者您可以直接更新
UPDATE tbl_l_contact_fund
SET contactID = (SELECT MIN(ContactID)
FROM tbl_contact cr
WHERE ContactName in
(Select ContactName
FROM tbl_contact
WHERE ContactID = a.contactID))
FROM tbl_l_contact_fund a
GO
DELETE tbl_contact WHERE ContactID NOT IN (SELECT MIN(contactID) contactID
FROM tbl_contact GROUP BY ContactName)
答案 1 :(得分:0)
这里你去找完整的sql
UPDATE a
SET a.contactid = c.contactid
FROM tbl_l_contact_fund a inner join
tbl_contact b on a.contactid = b.contactid
inner join (
SELECT * FROM tbl_contact a
where a.contactid in (SELECT min(b.contactid)
FROM tbl_contact b
WHERE b.contactname = a.contactname)
) c
on c.contactname = b.contactname
DELETE from tbl_contact a
where a.contactid not in (SELECT min(b.contactid)
FROM tbl_contact b
WHERE b.contactname = a.contactname)
答案 2 :(得分:0)
低于概念。
Update tbl_l_contact_fund tt
JOin
(
Select realId, id, name from tbl_contact ac
JOIN
(select min(Id) realId, name from tbl_contact group by Name) dt
on dt.Name=ac.Name
) ot on ot.id=tt.id
Set tt.id=ot.realid
答案 3 :(得分:0)
DELETE A
FROM tbl_contact A
INNER JOIN tbl_l_contact_fund B ON A.contactID = B.contactID