MySQL语句在不使用pivot函数或union的情况下透视表

时间:2018-03-29 10:23:09

标签: mysql

不使用pivot / unpivot函数或union,是否可以更改此数据:

+----+--------+---------+
| id | name   | surname |
+----+--------+---------+
| 1  | john   | smith   |
| 2  | jack   | brown   |
+----+--------+---------+

进入这个:

+----+-------------+
| id | data        |
+----+-------------+
| 1  | john        |
| 1  | smith       |
| 2  | jack        |
| 2  | brown       |
+----+-------------+

2 个答案:

答案 0 :(得分:0)

你可以使用光标

drop procedure if exists p;
delimiter $$
CREATE  PROCEDURE `p`()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
begin 
    declare vid int(8);
    declare vname varchar(15);
    declare vsurname varchar(15);
    declare done int default 0;
    declare cname cursor for select id,name,surname from t id;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    open cname;
    cursorloop:loop
    fetch cname into vid,vname,vsurname;
    if done = true then  
        leave cursorloop;
    end if;  
    insert into t1 (id,name) select vid,vname;
    insert into t1 (id,name) select vid,vsurname;
    end loop cursorloop;
    close cname;
end $$
delimiter ;

drop table if exists t,t1;
create table t( id int, name varchar(20), surname varchar(20));
create table t1(id int, name varchar(20));
insert into t values
( 1  , 'john'   , 'smith'),
( 2  , 'jack'   , 'brown');

call p();

MariaDB [sandbox]> select * from t1;
+------+-------+
| id   | name  |
+------+-------+
|    1 | john  |
|    1 | smith |
|    2 | jack  |
|    2 | brown |
+------+-------+
4 rows in set (0.00 sec)

但你为什么不使用工会?

答案 1 :(得分:0)

使用cross join和case语句获取姓名或姓氏。

select rn as id, (case when  id=rn then name else surname end) as `data`
from
(
select t1.id, t1.name, t2.surname, t2.rn
from myTable t1
cross join (
   select surname, (@r2:=@r2+1) as rn 
   from myTable, (select @r2:= 0) r) t2
) tab

Result:
id  data
1   jon
1   smith
2   brown
2   jack