2017-01-31 14 views
0

我想选择列中没有重复值的行。我的意思是,如果有一排| 2 | 1 |和另一个与| 1 | 2 |在目前的选择中,我只想显示其中的一个。sql选择没有重复在这两列

+------+------+ 
| id1 | id2 | 
+------+------+ 
| 2 | 1 | 
| 4 | 3 | 
| 3 | 4 | 
| 1 | 4 | 
+------+------+ 

所以在上面的例子中,它将只选择第一个,最后一个和第二个或第三个行。

也可以用另一个表中的字符串'TITLE'替换这些值。

表值:

+----+----------+ 
| id | title | 
+----+----------+ 
| 1 | title1 | 
| 2 | title2 | 
| 3 | title3 | 
| 4 | title4 | 
+----+----------+ 

使最终选择将有行只有冠军。

回答

2

您可以使用leastgreatest来执行此操作。 least得到id1,id2和greatest的较低值,得到id1,id2的较大值。

select distinct least(id1,id2),greatest(id1,id2) 
from t 

实际上,上面生成的行不在表中。为了避免它,你需要一个带有派生表的left join

select t1.id1,t1.id2 
from t t1 
left join (select least(id1,id2) as id1,greatest(id1,id2) as id2 
      from t 
      group by least(id1,id2),greatest(id1,id2) 
      having count(*) > 1 
     ) t2 on t2.id1=t1.id1 and t2.id2=t1.id2 
where t2.id1 is null and t2.id2 is null 

编辑:基于从不同的表拿到冠军串ID的

select t1.id1,t1.id2,tt1.title,tt2.title 
from t t1 
left join (select least(id1,id2) as id1,greatest(id1,id2) as id2 
      from t 
      group by least(id1,id2),greatest(id1,id2) 
      having count(*) > 1 
     ) t2 on t2.id1=t1.id1 and t2.id2=t1.id2 
join titles tt1 on tt1.id=t1.id1 --use a left join if the titles table won't have all the id's 
join titles tt2 on tt2.id=t1.id2 --use a left join if the titles table won't have all the id's 
where t2.id1 is null and t2.id2 is null 
+0

哇,这真的帮助。你还可以帮助用本表中存储的值替换此表中的当前值吗?如果我有每个id的字符串值的表'值',我怎么只有打印(选择)的字符串? – hvertous

+0

请显示一些示例数据。 –

+0

我有另一个'值''两栏:'id'和字符串'标题'。我需要用“标题”替换OP中选择的id。我希望我能更清楚地说明 – hvertous