[英]How can I get a record which has two corresponding columns which are multiple in SQL?
For example, I have two tables:例如,我有两个表:
ID | Name
------------
1 | test 1
2 | test 2
ID2| ID | Age
--------------
1 | 1 | 18
2 | 1 | 18
3 | 1 | 19
4 | 2 | 18
5 | 2 | 19
I want to have all records that have columns which are multiple in name with age but I don't know how to do that.我想拥有所有列的记录,这些列的名称与年龄有多个,但我不知道该怎么做。
I want an output like this:我想要这样的输出:
Name | Age
--------------------
test 1 | 18
test 1 | 18
Can anyone help me?谁能帮我?
Try following query:尝试以下查询:
Select t1.*, t2.*
from table1 t1
join table2 t2
on t1.id = t2.id
join (select id, age
from table2
group by id, age
having count(*) > 1
) t3
on t1.id = t2.id and t2.id = t3.id and t2.age = t3.age
Use exists
:使用
exists
:
select t.*
from t
where exists (select 1
from t t2
where t2.name = t.name and t2.age = t.age and
t2.id <> t.id
);
With an index on (name, age, id)
, this should be the fastest approach.使用
(name, age, id)
上的索引,这应该是最快的方法。
You can also use an IN
on tupples.您还可以
IN
上使用IN
。
And a GROUP BY can be combined with a HAVING to only get those that have duplicate (name, age).并且 GROUP BY 可以与 HAVING 结合使用,以只获取那些重复的(姓名、年龄)。
SELECT t1.Name, t2.Age
FROM YourTable2 t2
LEFT JOIN YourTable1 t1 ON t1.ID = t2.ID
WHERE (t2.ID, t2.Age) IN (
SELECT ID, Age
FROM YourTable2
GROUP BY ID, Age
HAVING COUNT(*) > 1
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.