Mysql
 sql >> Base de données >  >> RDS >> Mysql

Instruction MySQL pour un tableau croisé dynamique sans utiliser la fonction pivot ou une union

Eh bien, vous pouvez utiliser un curseur

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)

Mais pourquoi n'utiliseriez-vous pas un syndicat ?