sql:选择行,其中一些值相等(不是全部)
sql: selecting rows, in which some values are equal (not all)
前置条件:
Table,喜欢
id value1 value2 value3
1 x y z
2 x y x
3 x z y
4 y x z
5 x x z
任务:进行查询,这将 select 所有行,其中 "pairs" (值 1 和值 2)按行相等(例如,对于我们的案例,结果应该是第一行和第二行:
id value1 value2 value3
1 x y z
2 x y x
我们不知道 table 中可能有什么值。
所以,这就是重点。
select * from your_table
where id in
(
select id
from your_table
group by value1, value2
having count(*) > 1
)
您可以使用 window 函数执行此操作:
select t.*
from (select t.*, count(*) over (partition by value1, value2) as cnt
from t
) t
where cnt >= 2;
您可以使用 INNER JOIN
操作:
SELECT t1.id, t1.value1, t1.value2
FROM mytable AS t1
INNER JOIN mytable AS t2
ON t1.id <> t2.id AND t1.value1 = t2.value1 AND t1.value2 = t2.value2
select t1.* from Table t1, Table t2
where t1.value1 =t2.value1
and t1.value2=t2.value2
and t1.id<>t2.id
and t1.value1 <>t1.value2
前置条件:
Table,喜欢
id value1 value2 value3
1 x y z
2 x y x
3 x z y
4 y x z
5 x x z
任务:进行查询,这将 select 所有行,其中 "pairs" (值 1 和值 2)按行相等(例如,对于我们的案例,结果应该是第一行和第二行:
id value1 value2 value3
1 x y z
2 x y x
我们不知道 table 中可能有什么值。
所以,这就是重点。
select * from your_table
where id in
(
select id
from your_table
group by value1, value2
having count(*) > 1
)
您可以使用 window 函数执行此操作:
select t.*
from (select t.*, count(*) over (partition by value1, value2) as cnt
from t
) t
where cnt >= 2;
您可以使用 INNER JOIN
操作:
SELECT t1.id, t1.value1, t1.value2
FROM mytable AS t1
INNER JOIN mytable AS t2
ON t1.id <> t2.id AND t1.value1 = t2.value1 AND t1.value2 = t2.value2
select t1.* from Table t1, Table t2
where t1.value1 =t2.value1
and t1.value2=t2.value2
and t1.id<>t2.id
and t1.value1 <>t1.value2