views:

43

answers:

4

I want one record from a table having unique Primary Key and duplicate Foreign Key

Please see attached image below

alt text

Thanks

A: 

Primary key by definition means there will only be one, so your question appears to actually appears to be are the any rows with more than 1 child row:

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

This would retrieve all unique fk and textVal values from the table:

select distinct fk, textVal from myTable
Oded
A: 

Have a look at this example.

This will find you all IDs from TABLE1 where it is duplicated in TABLE2 as a 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
astander
A: 
Select fk, Count(*) 
from table1
group by fk
having count(*) > 1
Spence