MySql查询2列中相同值的行

时间:2017-04-19 15:08:52

标签: mysql

我有一张桌子(MyTable);

 id   date        value1   value2
    1    2016-09-16    1       null
    2    2016-09-16    null    null
    3    2016-09-16    3       null
    4    2017-01-16    2       null
    5    2017-01-16    null     1
    6    2017-01-16    null     34
    7    2017-01-16    null      3

需要它返回value1和value2中具有匹配值的行 在上面我需要返回第1,3,5,7行。

如果可能,按日期排序,值2

3 个答案:

答案 0 :(得分:1)

试试这个:

select 
    *
from
    my_table t
where
    t.value1 in
        (select value2 from my_table)
or  
    t.value2 in
        (select value1 from my_table)
order by 
    t.date, t.value2

答案 1 :(得分:0)

带连接的不同格式输出:

SELECT
   myt.id as 'ID1',
   myt2.id as 'ID2',
   myt.value1 as 'Value1',
   myt2.value2 as 'Value2'
FROM
   MyTable as myt
      INNER JOIN MyTable as myt2
WHERE
   myt.value1 = myt2.value2

收率:

ID1       ID2      Value1     Value2
1          5         1          1
3          7         3          3

答案 2 :(得分:-2)

只需添加' Where'带有' value1'的条款IS NOT NULL和' value2' IS NOT NULL