如何将两列从同一个表连接到单个列

时间:2015-02-02 20:46:51

标签: mysql sql join inner-join

我试图将具有相同类型的两列的结果导入单列,例如

table 
id      secId
1         2
3         1
5         1
1         4

我想像id或secId = 1

那样检索它们
id
2
3
4
5

我尝试过内连接,但它为我提供了2列数据冗余

4 个答案:

答案 0 :(得分:4)

您不需要任何Join,这个简单的查询就可以了

select if(id=1, secId, id)
  from yourTable
  where id = 1 or secId = 1;

您选择idsecId等于1的所有数据,具体取决于两者中的哪一项等于显示1的{​​{1}}或secId

假设这两个值中只有一个可以是id

如果有可能有两个值,那么你可以使用union语法作为@AndreasWederbrand描述。

答案 1 :(得分:2)

您可以使用union来获取

select id from yourTable where secId = 1
union
select secId from yourTable where id = 1

如果您不喜欢union all也执行union

的方式,请使用distinct

答案 2 :(得分:0)

您还可以使用CASE语句在两列之间进行选择。

SELECT CASE 
        WHEN id = 1 --if this is a 1 select the other col
            THEN secId
        ELSE id --otherwise just select this column
        END AS newCol
FROM yourTable
WHERE id = 1
    OR secId = 1

答案 3 :(得分:0)

以下是最简单的代码:

Select Case When id = 1 then secId end ID from yourtable
相关问题