0

这看起来很荒谬,但我就是无法做到这一点 - 任何帮助都非常感谢!

基本上:我正在使用 RMySQL 执行一些简单的 SQL,以便了解 SQL 的工作原理。select作为一个简单的示例,我想将几​​个 SQL 查询链接在一起。这在 RMySQL PDF 中有介绍 - 但其中的示例似乎是不正确的语法(http://cran.r-project.org/web/packages/RMySQL/RMySQL.pdf,第 3 页,示例 6)。

如果我有三个查询,请这样说:

q1 <- "SELECT db.table FROM table WHERE stuff = 'blah' "
q2 <- "SELECT db.other_table FROM other_table WHERE stuff = 'different blah' "
q3 <- "SELECT db.table2 FROM table2 WHERE table2 = 1000"

并尝试paste如下:

script <- paste(q1, q2, q3, sep=";")

结果是

> script
[1] "SELECT db.table FROM table WHERE stuff = 'blah' ;SELECT fb.other_table FROM
other_table WHERE stuff = 'different blah' ;SELECT db.table2 FROM table2 WHERE table2 =
'1000'

所以调用dbSendQuery显然失败了。

我试过\"了,但这也不起作用:

q1 <- "SELECT db.table FROM table WHERE stuff = 'blah' \" "
q2 <- "SELECT db.other_table FROM other_table WHERE stuff = 'different blah' \""
q3 <- "SELECT db.table2 FROM table2 WHERE table2 = 1000 \" "

script <- paste(q1, q2, q3, sep=";")

> script
[1] "SELECT db.table FROM table WHERE stuff = 'blah' \" ;  ;SELECT db.other_table FROM
other_table WHERE stuff = 'different blah' \";SELECT db.table2 FROM table2 WHERE table2
= 1000 \" "

谁能指出我做错了什么?

编辑:只是为了澄清,通过 RMySQL 执行如下:

my.queries <- dbGetQuery(my.con, script, client.flag = CLIENT_MULTI_STATEMENTS)

根据 RMySQL 手册,我得到

RS-DBI driver: (could not run statement: You have an error in your SQL syntax;

据推测,这是因为paste函数的结果应该是:

"SELECT db.table FROM table WHERE stuff = 'blah'" ;"SELECT fb.other_table FROM
other_table WHERE stuff = 'different blah'" ;"SELECT db.table2 FROM table2 WHERE table2
= '1000'"

每个单独的查询都工作得很好,所以我假设是我的paste命令导致了这个问题。

编辑:为了简化这一点:假设我有两个字符串,如下所示:

t1 <- "the 'stuff'"
t2 <- "more 'stuff'"
paste(t1, t2, sep=";")
[1] "the 'stuff' ; more 'stuff' "

我想要的是粘贴命令的结果是"the 'stuff'";"more 'stuff'".

4

1 回答 1

1

您必须将参数传递client.flag = CLIENT_MULTI_STATEMENTS给函数dbConnection,而不是dgGetQuery.

然后,您的第一种方法应该有效:

q1 <- "SELECT db.table FROM table WHERE stuff = 'blah' "
q2 <- "SELECT db.other_table FROM other_table WHERE stuff = 'different blah' "
q3 <- "SELECT db.table2 FROM table2 WHERE table2 = 1000"

script <- paste(q1, q2, q3, sep=";")
于 2014-01-26T21:37:45.850 回答