简体   繁体   中英

How to select a record which has a foreign key with more than value?

I am a newbie with PlSQL. I have this table which represents relation between 2 tables:

ID T1Id T2Id
-- ---- ----
 1    1    1
 2    2    1
 3    2    2
 4    2    3
 5    3    1
...

I have values in 2nd column(T1Id) which could have one or more values from 3rd one(T2Id). My question is how to select only T1Id values which have more than 1 T1Id value.

Do you have any idea?

if you only want the T1Id values where there is more than one in the table you can use the below.

select T1Id, count(T1Id) as countT1 from yourTable
group by T1Id
having count(T1Id) > 1

If you wanted to select other columns you can use row partition to achieve this

SELECT *
  FROM (SELECT a.*, COUNT (*) OVER (PARTITION BY t1id) AS countT1
          FROM yourTable a)
 WHERE countT1 > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM