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

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


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

并用另一个表中的字符串“ TITLE”替换这些值。

表值:

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


因此最终选择将仅在行中显示标题。

最佳答案

您可以使用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

关于mysql - sql select在两列中都没有重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41967116/

10-10 11:57