MYSQL:如何用前一个条目填充列中的空值?

时间:2016-02-15 00:50:41

标签: mysql

我有一个出口到CSV的程序,但在最烦躁的地方留下了空白。我想在同一行查看运营商和目的地,目前运营商位于目的地上方一行,如下所示:

我有一个类似如下的数据库:
     |Key|Carrier ||Destination|
     |-------------------------|
     | 1 | HULL2 || |
     | 2 | || C14A102 |
     | 3 | DONC1 || |
     | 4 | || D15A012 |

我想要的是什么:

 |Key|Carrier ||Destination|
 |-------------------------|
 | 1 | HULL2  ||           |
 | 2 | HULL2  ||  C14A102  |
 | 3 | DONC1  ||           |
 | 4 | DONC1  ||  D15A012  |

或者使用来自载体列的信息插入新列。

很抱歉,如果这让我感到困惑,请他解释一下!

詹姆斯

2 个答案:

答案 0 :(得分:1)

这是一个解决方案,通过克隆另一个表然后将其删除:

CREATE TABLE t1(Key_id INT PRIMARY KEY, Carrier CHAR(20), Destination CHAR(20));
INSERT INTO t1 VALUES(1, 'HULL2', ''),(2,'','C14A102'),(3,'DONC1',''),(4,'','D15A012');

CREATE TABLE t2 LIKE t1;
INSERT INTO t2 SELECT * FROM t1;

SELECT * FROM t1;
UPDATE t1 SET Carrier = 
    (
    SELECT t2.Carrier
    FROM t2
    WHERE t2.Key_id < t1.Key_id AND t2.Carrier != ''
    ORDER BY t2.Key_id DESC
    LIMIT 1
    )
WHERE Carrier = '';
SELECT * FROM t1;

DROP TABLE t2;

输出:

mysql> SELECT * FROM t1;
+--------+---------+-------------+
| Key_id | Carrier | Destination |
+--------+---------+-------------+
|      1 | HULL2   |             |
|      2 |         | C14A102     |
|      3 | DONC1   |             |
|      4 |         | D15A012     |
+--------+---------+-------------+
4 rows in set (0.00 sec)

mysql> UPDATE t1 SET Carrier =
    -> (
    -> SELECT t2.Carrier
    -> FROM t2
    -> WHERE t2.Key_id < t1.Key_id AND t2.Carrier != ''
    -> ORDER BY t2.Key_id DESC
    -> LIMIT 1
    -> )
    -> WHERE Carrier = '';
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> SELECT * FROM t1;
+--------+---------+-------------+
| Key_id | Carrier | Destination |
+--------+---------+-------------+
|      1 | HULL2   |             |
|      2 | HULL2   | C14A102     |
|      3 | DONC1   |             |
|      4 | DONC1   | D15A012     |
+--------+---------+-------------+
4 rows in set (0.00 sec)

答案 1 :(得分:0)

假设列&#39;键&#39;可以通过这种方式信任,我会使用自联接更新,其中联接使用key = key+1,然后确保它只影响偶数行。

UPDATE tablename as even_row JOIN tablename as odd_row 
ON even_row.Key = odd_row.Key + 1 
SET even_row.Carrier = odd_row.Carrier 
WHERE odd_row.Key % 2;