我的表格a
包含两列id
,value
,如下所示:
+-------+-----------+
| id | value |
+-------+-----------+
| 1 | 12 |
| 2 | 15 |
| 3 | 30 |
| 4 | 40 |
| 5 | 45 |
| 6 | 50 |
| 7 | 80 |
| 8 | 90 |
+-------+-----------+
我想编写一个查询来创建一个值更大但最接近shiftedValue
的新列value
。如果value
已经是最大的,我们将shiftedValue
设置为inf
,请参阅最后一行。所需的表格如下,
+-------+-----------+-------------+
| id | value | shiftedValue|
+-------+-----------+-------------+
| 1 | 12 | 15 |
| 2 | 15 | 30 |
| 3 | 30 | 40 |
| 4 | 40 | 45 |
| 5 | 45 | 50 |
| 6 | 50 | 80 |
| 7 | 80 | 90 |
| 8 | 90 | inf |
+-------+-----------+-------------+
有什么建议吗?
答案 0 :(得分:1)
您可以使用:
SELECT a.id, a.value, IFNULL(b.value, 'inf') shiftedValue
FROM a as a LEFT JOIN a as b ON a.id = b.id - 1
您可以在此处添加逻辑,以便在b.id为NULL时添加inf
。
答案 1 :(得分:0)
我认为最简单的方法如下:
将表导出到csv文件
SELECT * FROM a
INTO OUTFILE "your_csv_file.csv"
FIELD ENCLOSED BY '"'
TERMINATED BY ';'
ESCAPED BY '"'
LINES TERMINATED BY '\r\n'
inf
);您可以使用Excel轻松完成此操作将文件导入MySql
LOAD DATA INFILE 'your_csv_file.csv'
INTO TABLE your_table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 ROWS;