sql select,两列中没有重复项

时间:2017-01-31 20:42:57

标签: mysql sql select duplicates

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

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

因此在上面的示例中,它将仅选择第一行,最后一行和第二行或第三行。

并将这些值替换为字符串' TITLE'从另一张桌子。

表值:

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

这样最终选择只有行标题。

1 个答案:

答案 0 :(得分: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
相关问题