How can I query table 1 to give me records where id2 exists more than once in id1?
table 1
id1, id2
1,100
1,99
1,98
2,100
2,101
2,102
So the desired result would be
1,100
2,100
How can I query table 1 to give me records where id2 exists more than once in id1?
table 1
id1, id2
1,100
1,99
1,98
2,100
2,101
2,102
So the desired result would be
1,100
2,100
Your best bet here is a subquery to get id2
values that show up more than once in your table. Then return records from the table that contain those id2
values. There's a few ways to do this.
Here is one using the IN
clause and just hitting a list returned by a subquery:
SELECT id1, id2
FROM table1
WHERE id2 IN (SELECT id2 FROM table1 GROUP BY id2 HAVING count(*) > 1)
And another using a correlated subquery which may prove useful if your data is larger
SELECT id1, id2
FROM table1 t1
WHERE EXISTS (SELECT id2 FROM table1 WHERE t1.id2 = id2 GROUP BY id2 HAVING count(*) > 1)
You can use the following query to determine if an id exists in more than one instance of another column:
select id1, id2
from table
group by id2
having count(*) > 1
You can use une a join with id2 like this:
SELECT
t1.id1
,t1.id2
FROM
table1 as t1
inner join table1 as t2 on t2.id2 = t1.id2