Mysql 如何将同一表中的两列合并为一列
例如,我试图将两列相同类型的结果转换为一列Mysql 如何将同一表中的两列合并为一列,mysql,sql,join,inner-join,Mysql,Sql,Join,Inner Join,例如,我试图将两列相同类型的结果转换为一列 table id secId 1 2 3 1 5 1 1 4 我想像这样检索它们,其中id或secId=1 id 2 3 4 5 我尝试过内部连接,但它给了我两列数据冗余您不需要任何连接为此,这个简单的查询就可以了 select if(id=1, secId, id) from yourTable where id = 1 or secId = 1; 然后,根据显
table
id secId
1 2
3 1
5 1
1 4
我想像这样检索它们,其中id或secId=1
id
2
3
4
5
我尝试过内部连接,但它给了我两列数据冗余您不需要任何
连接
为此,这个简单的查询就可以了
select if(id=1, secId, id)
from yourTable
where id = 1 or secId = 1;
然后,根据显示的secId
或id
中哪一个等于1
,选择所有id
或secId
的数据
这里假设两个值中只有一个可以是1
如果有可能有两个值,那么您可以使用@AndreasWederbrand所描述的联合语法。您不需要任何
连接
,这个简单的查询就可以了
select if(id=1, secId, id)
from yourTable
where id = 1 or secId = 1;
然后,根据显示的secId
或id
中哪一个等于1
,选择所有id
或secId
的数据
这里假设两个值中只有一个可以是1
如果可能有两个值,则可以使用@AndreasWederbrand所述的union语法。可以使用
union
获得该值
select id from yourTable where secId = 1
union
select secId from yourTable where id = 1
使用
union all
如果您不喜欢union
也执行distinct
的方式,您可以使用union
来实现这一点
select id from yourTable where secId = 1
union
select secId from yourTable where id = 1
使用union all
如果您不喜欢union
也执行distinct
的方式,也可以使用语句在两列之间进行选择
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
您还可以使用语句在这两列之间进行选择
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
下面是最简单的代码:
Select Case When id = 1 then secId end ID from yourtable
下面是最简单的代码:
Select Case When id = 1 then secId end ID from yourtable
好的,那么如果其中一列是
1
你想从另一列得到值吗?是的,如果其中一列有1,我想检索另一列为什么需要这个?好的,那么如果其中一列是1
你想从另一列得到值吗?是的,如果其中一列有1,我想检索另一列为什么需要这个?