我尝试插入,选择,数组,mysql

时间:2018-07-06 15:42:15

标签: mysql

问题是: 假设我有这张桌子:

ID DATO1 DATO2 DATO3
1----A-----B---2020
2----A-----F---2020
3----A-----F---2020
4----D-----G---2020
5----E-----G---2021
6----A-----I---2021

我想插入一个

INSERT INTO datos1(Column1,Column2,Column3,Column4) 
values ((IFNULL(SELECT `DATO1(0) FROM datos WHERE DATO3=2020),''),
        (IFNULL(SELECT DATO1(1) FROM datos WHERE DATO3=2020),''),
        (IFNULL(SELECT DATO1(2) FROM datos WHERE DATO3=2020),''),
        (IFNULL(SELECT DATO1(3) FROM datos WHERE DATO3=2020),''));`

他怎么做?

非常感谢

1 个答案:

答案 0 :(得分:0)

我们可以这样

INSERT INTO datos1 (Column1,Column2,Column3,Column4)
SELECT IFNULL( SELECT c1.DATO1 FROM datos c1 WHERE c1.DATO3=2020 ORDER BY c1.id LIMIT 0,1 ),'') AS Column1
     , IFNULL( SELECT c2.DATO1 FROM datos c2 WHERE c2.DATO3=2020 ORDER BY c2.id LIMIT 1,1 ),'') AS Column2
     , IFNULL( SELECT c3.DATO1 FROM datos c3 WHERE c3.DATO3=2020 ORDER BY c3.id LIMIT 2,1 ),'') AS Column3
     , IFNULL( SELECT c4.DATO1 FROM datos c4 WHERE c4.DATO3=2020 ORDER BY c4.id LIMIT 3,1 ),'') AS Column4