![](/img/trans.png)
[英]what will be the sql query for checking same pairs of column values in a table?
[英]Exclude same pairs from sql query
我有一个表中有两列:
primId column1 column2
1 98 62
2 62 98
3 3 105
4 105 3
5 11 4
我需要获得第二排,第四排,第五排。 如果98,62出现一次,则62,98不能出现(如果可能,我需要最新值)。 我已从这个链接中获取帮助从SQL Join中删除镜像对 ,但没有运气。 这些值在较大或较小程度上彼此无关。 请告诉我如何才能得到这个结果。 这可能与Sql查询。 谢谢
你可以这样做:
select t1.*
from yourTable t1
left join
yourTable t2
on t1.column1 = t2.column2 and
t1.column2 = t2.column1
where t2.column1 is null or
t1.column1 > t1.column2
镜像行将被连接,由于第二个where
条件,您将只接受它们一次,并且未镜像的行将不会被连接,因此您将使用第一个where
条件获取它们。
编辑
要让最后一对夫妇返回,您可以使用此方法
select t1.*
from yourTable t1
join (
select max(primId) as primId,
case when column1 > column2 then column2 else column1 end c1,
case when column1 < column2 then column2 else column1 end c2
from yourTable
group by case when column1 > column2 then column2 else column1 end,
case when column1 < column2 then column2 else column1 end
) t2
on t1.primId = t2.primId
无论顺序如何,内部查询将返回每对情侣的最高primId
。 将它与源表连接,您可以将其用作过滤器。
你可以看到它在这里工作
您可以使用以下查询:
SELECT DISTINCT LEAST(column1, column2) AS column1,
GREATEST(column1, column2) AS column2
FROM mytable
注意:如果字段顺序与您无关,则上述查询有效。 否则你必须使用像@Stefano建议的JOIN
。
如果表中存在查询结果集中的行无关紧要,则可以使用least
和greatest
以便检索每对中的一行。
select distinct least(column1,column2) as col1, greatest(column1,column2) as col2
from tablename
如果检索到该行已存在于表,使用以前的查询并将它加入到现有的表。
select t.column1,t.column2
from tablename t
left join (select least(column1,column2) as col1, greatest(column1,column2) as col2
from tablename
group by least(column1,column2), greatest(column1,column2)
having count(*)>1
) x on x.col1=t.column1 and x.col2=t.column2
where x.col1 is null and x.col2 is null
如果您想确保保留原始对(因此不允许4,1作为输出),那么以下应该非常有效:
select t.*
from t
where t.column1 <= t.column2
union all
select t.*
from t
where t.column1 > t.column2 and
not exists (select 1 from t t2 where t2.column1 = t.column2 and t2.column2 = t.column1);
为获得最佳性能,您需要t(column1, column2)
上的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.