Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column of data to an existing mySQL table

Tags:

php

mysql

I have a basic SQL problem that's been driving me mad. If I have a mySQL table e.g below. How would I add another 80+ values to Column 2 starting from the first empty row (in this example row 3).

I've been trying a number of queries using INSERT or UPDATE but the closest I've got is to add the values to column 2 starting from the last defined ID value (e.g. row 80ish).

   ID  |    Column 2    |
--------------------------------
  1    |    value       |
  2    |    value       |
  3    |                |
  4    |                |
  5    |                |

etc

The real table has around 10 columns, all with data in but I just need to add content (a list of around 80 different strings in CSV format to one of the columns)

I'd appreciate it if anyone could point me in the right direction.

like image 672
Andrew Scrivener Avatar asked Oct 21 '22 07:10

Andrew Scrivener


1 Answers

I'd load the data into a separate table with the same structure and then update the target table using join or subquery to determine which columns are currently empty.

i.e. load interim table and then:

update target_table set column2 = (select column2 from interim_table where ... 
where column2 is null

(slow but intuitive)

update target table, interim_table 
set target table.column2 = interim_table.column2 
where target table... = interim_table...
and target_table.column2 is null

(better performance)

like image 173
davek Avatar answered Oct 29 '22 17:10

davek