DISTINCT语句如何合并一个表中的两行

时间:2018-05-04 11:24:12

标签: mysql sql distinct

请给出任何解决方案如何合并一个表中的两行,然后如何使用distinct

查询:

select distinct  uid , r_uid from messenger  where uid=213 or r_uid =213 

我得到了像这样的输出

      uid     r_uid
     --------------
      213     239
      239     213
     -----------------

但我们需要这样

           new id
        -----------
            239
         ---------

请事先告诉我任何解决方案我是MySQL新手

2 个答案:

答案 0 :(得分:3)

使用union

select uid as new_id from messenger
where uid = 213  
union
select r_uid from messenger
here r_uid = 213;   

答案 1 :(得分:3)

我认为您正在寻找"其他价值。最简单的方法可能是:

select uid
from messenger
where r_uid = 213
union -- intentional, remove duplicates
select r_uid
from messenger
where uid = 213;

您也可以使用case

执行此操作
select distinct (case when r_uid = 213 then uid else r_uid end)
from messenger
where 213 in (r_uid, uid);