我想使用ALTER TABLE
andUPDATE
语句在我的表中添加一列,而不是重新创建完整的表。
在我的UPDATE
语句中使用子查询时,我没有得到我期望的输出。
构建可重现的数据
library(dplyr)
library(dbplyr)
library(DBI)
con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")
copy_to(con, iris[c(1,2,51),],"iris")
tbl(con,"iris")
# # Source: table<iris> [?? x 5]
# # Database: sqlite 3.19.3 []
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <chr>
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
# 3 7.0 3.2 4.7 1.4 versicolor
在单独的表中创建新列
DBI::dbSendQuery(con, "CREATE TABLE new_table AS SELECT t2.new_col from
iris t1 inner join
(SELECT Species, sum(`Sepal.Width`) as new_col FROM iris GROUP BY Species) t2
on t1.Species = t2.Species")
tbl(con,"new_table")
# # Source: table<new_table> [?? x 1]
# # Database: sqlite 3.19.3 []
# new_col
# <dbl>
# 1 6.5
# 2 6.5
# 3 3.2
在旧表中创建新列
DBI::dbSendQuery(con, "ALTER TABLE iris ADD COLUMN new_col DOUBLE")
尝试从new_table
那里插入新列
DBI::dbSendQuery(con, "UPDATE iris SET new_col = (SELECT new_col FROM new_table)")
tbl(con,"iris")
# # Source: table<iris> [?? x 6]
# # Database: sqlite 3.19.3 []
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species new_col
# <dbl> <dbl> <dbl> <dbl> <chr> <dbl>
# 1 5.1 3.5 1.4 0.2 setosa 6.5
# 2 4.9 3.0 1.4 0.2 setosa 6.5
# 3 7.0 3.2 4.7 1.4 versicolor 6.5
如您所见, mynew_col
仅包含6.5
我希望3.2
在最后一行中具有的值。我怎样才能解决这个问题 ?