Mysql 从sql查询中排除相同的对
我有一个表,其中有两列:Mysql 从sql查询中排除相同的对,mysql,sql,Mysql,Sql,我有一个表,其中有两列: primId column1 column2 1 98 62 2 62 98 3 3 105 4 105 3 5 11 4 我要去第二排,第四排,第五排。 如果98,62出现过一次,则62,98无法出现。如果可能,我需要最新的值。 我已经从这个链接获得了帮助,但没有得到任何运气。 这些值在较大或较小程度上互不相关
primId column1 column2
1 98 62
2 62 98
3 3 105
4 105 3
5 11 4
我要去第二排,第四排,第五排。
如果98,62出现过一次,则62,98无法出现。如果可能,我需要最新的值。
我已经从这个链接获得了帮助,但没有得到任何运气。
这些值在较大或较小程度上互不相关。
请告诉我如何才能得到这个结果。
这在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 proposes之类的联接。当查询结果集中的行是否存在于表中无关紧要时,您可以使用最小值和最大值,以便每对检索一行
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);
为了获得最佳性能,您需要在tcolumn1的第2列上建立索引。是否必须删除这些行?或者只选择它们?只选择它们最新的值,如何选择?您是否也有ID列或时间戳列?是的,有一个主自动递增ID,它提供的行数多于所需的行数。@user1578460。这是因为逻辑不正确。例如,这会带来column1>column2的每一行。