I want one record from a table having unique Primary Key and duplicate Foreign Key
Please see attached image below
Thanks
I want one record from a table having unique Primary Key and duplicate Foreign Key
Please see attached image below
Thanks
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
)
This would retrieve all unique fk and textVal values from the table:
select distinct fk, textVal from myTable
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