change a field and port mysql table data via script ?

橙三吉。 提交于 2019-12-11 02:39:12

问题


mysql> desc oldtable;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| uid           | int(11)      | NO   | PRI | NULL    | auto_increment |
| active        | char(1)      | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+


mysql> desc newtable;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| uid        | int(11)      | NO   | PRI | NULL    | auto_increment |
| active     | tinyint(1)   | NO   |     | 0       |                |
+------------+--------------+------+-----+---------+----------------+

I would like to port data (dump) from oldtable into newtable. One issue is, earlier the table used char(1) for active which stores value either 'Y' or 'N'. Now the newtable stores it as int either 1 or 0.

How can i fix this before porting data? Should I use shell script for such fix & porting ? Any sample scripts or tips :)


回答1:


INSERT INTO newtable 
SELECT uid,IF(active='Y',1,0) as active FROM oldtable

should do the trick




回答2:


INSERT INTO newtable (uid, active)
    SELECT uid, IF(active='Y', 1, 0) AS active
    FROM oldtable

docs for this syntax here: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html




回答3:


Joking version:

INSERT INTO newtable 
SELECT uid,FIELD(active,'Y') as active 
FROM oldtable


来源:https://stackoverflow.com/questions/9792443/change-a-field-and-port-mysql-table-data-via-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!