简体   繁体   中英

MySQL Moving table from varchar to int

I am moving an old Mantis table that had a varchar(64) category_id column to a new Mantis table that has a int(10) category_id column.

The simplified structure is as follows

bug_table (Old DB)

+----+-------------+-------------+--------+ | id | project_id | category_id | report | +----+-------------+-------------+--------+ | 1 | 0 | Server | crash | | 2 | 0 | Database | error | | 3 | 1 | Server | bug | | 4 | 1 | Server | crash | +----+-------------+-------------+--------+

category_table (New DB)

+----+------------+----------+ | id | project_id | name | +----+------------+----------+ | 0 | 1 | Server | | 1 | 1 | Database | | 2 | 2 | Server | | 3 | 2 | Database | +----+------------+----------+

I need a magical query that will replace category_id in the bug_table with the numerical category_id in the category_table . Thankfully I am able to match rows by project_id and categories by name .

Here is the query I am working on but have gotten stuck in the complexity

UPDATE bug_table b SET b.category_id = c.id USING category_table WHERE b.category_id = c.name

I like to approach such a task a little differently than you do for a new lookup/reference table.

  1. To me, the new category table would only have id and name columns. There are only two rows based on the sample data: Server and Database. Yes, I realize there could be other names, but those can easily be added, and should be added, before proceeding to maximize the id matching that follows.

  2. Next I would add a new column to the bug table that could be called 'category_new' with the data type that will store the new category id. Alternatively, you could rename the existing category_id column to category, and the new column for the id's could then be column_id.

  3. After all that is done then you can update the new column by joining the category on names and set the id that matches: ( note this assumes the non -alternative approach mentioned in step 2)

     UPDATE bug_table JOIN category_table ON bug_table.category_id = category_table.name SET bug_table.category_new = category_table.id 
  4. After that runs, check the new column to verify the updated id's.

  5. Finally, after successful update, now the old category_id column (with the names) from the bugs_table can be dropped, and the category_new column can be renamed as the category_id.

=====

Note that if you decide to go with the alternative column approach mentioned, of course the query will be similar but differ slightly. Then only a column drop is needed at the end

If there are other tables to apply the same category changes, the operation (basically steps 2 through 5) would be similar for those tables too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM