[英]How can I write a SQL query which ensures two columns are independently unique?
[英]How can I get a record which has two corresponding columns which are multiple in SQL?
例如,我有兩個表:
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
我想擁有所有列的記錄,這些列的名稱與年齡有多個,但我不知道該怎么做。
我想要這樣的輸出:
Name | Age
--------------------
test 1 | 18
test 1 | 18
誰能幫我?
嘗試以下查詢:
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
使用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
);
使用(name, age, id)
上的索引,這應該是最快的方法。
您還可以IN
上使用IN
。
並且 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.