I want to be able to add a column into an existing table
with its corresponding type.
This is how I tried it:
library("RMySQL")
# Connect to DB
v_db <- dbConnect(MySQL(),
user="USERNAME", password="PASSWORD",
dbname="DBNAME", host="localhost")
on.exit(dbDisconnect(v_db))
#Read in my new data (into R)
newcolumn <- read.csv("test.csv")
newcolumn
id datafornewcolumn
1 4
2 5
3 8
dbq <- dbSendQuery(v_db, "SELECT * FROM `EXISTINGTABLE`")
dbq <- fetch(dbq, n = -1)
dbq
id existing columns
1 ...
2 ...
3 ...
dbWriteTable(v_db, "EXISTINGTABLE", merge(dbq, newcolumn, by="id", all.x=TRUE), row.name=FALSE, overwrite=T)
But with that last statement I overwrite the existing table with the new one thereby losing all the corresponding variable types.
Then I tried a workaround. Write the new data into a new table
in SQL and after that merge that into the EXISTINGTABLE
. However, it seems I'm not able to do that corretly:
dbSendQuery(v_db, "create table workaround (id int not null primary key,
newcolumn DECIMAL(3,1))")
#write data into that new empty table called workaround --> works fine
dbWriteTable(v_db, "workaround", neu, row.name=FALSE, append=TRUE)
#something works...
dbSendQuery(v_db, "SELECT * FROM EXISTINGTABLE
LEFT JOIN workaround ON EXISTINGTABLE.id = workaround.id
UNION
SELECT * FROM EXISTINGTABLE
RIGHT JOIN workaround ON EXISTINGTABLE.id = workaround.id")
<MySQLResult:(29344,26,2)>
The result should look like this:
EXISTINGTABLE
id existingcolumns datafornewcolumn
1 ... 4
2 ... 5
3 ... 8