在R粘贴功能中混合单引号和双引号?

时间:2014-01-26 20:28:29

标签: mysql r paste double-quotes rmysql

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

基本上:我正在使用RMySQL来做一些简单的SQL,以便了解SQL的工作原理。作为一个简单的例子,我想将一些SQL select查询链接在一起。这在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'"

1 个答案:

答案 0 :(得分: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=";")