从具有唯一PK和重复FK的表中查找一条记录

时间:2010-01-20 08:54:06

标签: sql sql-server-2005 tsql

我想要一张具有唯一主键和重复外键的表中的一条记录

请参阅下面附图

alt text http://img413.imageshack.us/img413/9940/findduplicate.png

由于

4 个答案:

答案 0 :(得分:0)

主键定义意味着只有一个,所以你的问题看起来实际上似乎是任何行超过1行的行:

select * 
from table1 t
where exists (
    select id from table2 t2
    where t2.fkid = t.id
    group by t2.id
    having count(*) > 1
    )

答案 1 :(得分:0)

这将从表中检索所有唯一的fk和textVal值:

select distinct fk, textVal from myTable

答案 2 :(得分:0)

看看这个例子。

这将找到TABLE1中的所有ID,它在TABLE2中作为FOREIGN KEY重复

DECLARE @Table1 TABLE(
        id INT
)

DECLARE @Table2 TABLE(
        id INT,
        fkid INT
)

INSERT INTO @Table1 (id) SELECT 1
INSERT INTO @Table1 (id) SELECT 2
INSERT INTO @Table1 (id) SELECT 3

INSERT INTO @Table2 (id,fkid) SELECT 1, 1
INSERT INTO @Table2 (id,fkid) SELECT 2, 2
INSERT INTO @Table2 (id,fkid) SELECT 3, 2
INSERT INTO @Table2 (id,fkid) SELECT 4, 3
INSERT INTO @Table2 (id,fkid) SELECT 5, 3
INSERT INTO @Table2 (id,fkid) SELECT 6, 3

SELECT  t2.fkid
FROM    @Table2 t2
GROUP BY t2.fkid
HAVING COUNT(t2.fkid) > 1

答案 3 :(得分:0)

Select fk, Count(*) 
from table1
group by fk
having count(*) > 1