2013-06-05 21 views
3

EDIT-1如何在R中,使用REGEXP在sqlquery函數

我實際的數據庫是MSACCESS格式和我在RODBC包河的下面導入使用sqlQuery函數的數據是假的數據庫,我創建,以便我可以使用RSQLite包提供可重複的示例。我想用 sqlQuery函數使用正則表達式。 EDIT-1

以下的

結束是使用RSQLite包模擬數據庫和相關聯的查詢。 REGEX(或REGEXP)函數不起作用,我找不出原因。

data0 <- read.csv(textConnection(
'ID value 
P9W38 97 
P9W39 17 
P9W40 78 
P9W41 7 
P9W42_1 38 
P9W42 13 
P9W43 18 
P9W44 76 
P9W45 65 
P9W46 24 
P9W46_1 44 
P9W47 8 
P9W48 31 
P9W49 82 
P9W50 52 
P9W50_2 55 
P9W51 26 
P9W52 33 
P9W52_2 79 
P9W53 67 
P9W54 74 
P9W55 55' 
),sep='') 

dbWriteTable(con, "Mydata", data0) 

這些工作

dbGetQuery(con, paste0(' select * from Mydata where [ID] like \'P9W38\' ')) 
dbGetQuery(con, paste0(' select * from Mydata where [ID] like \'P9W42%\' ')) 

但這些不工作

dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEX \'P9W(38|40|50)\' ')) 
dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEX \'P9W(38|40|50)(_1){,1}\' ')) 

什麼建議嗎?

+0

由於'like'語句的工作,我預計'正則表達式'相同。抱歉,我是SQL新手,希望能更詳細地瞭解您的意見。我不明白我如何做你提到的過濾,除了在查詢語句 –

+0

@agstudy MySQL有一個[特定的擴展名](http://dev.mysql.com/doc/refman/5.1/en/regexp.html)到普通的SQL允許正則表達式。所以你會期望這種事情有效。 – nograpes

+0

@ Stat-R您是否通過另一個客戶端直接對您的MySQL數據庫嘗試了查詢?如果這不起作用,最好在這個問題上添加一個'mysql'標記。 – nograpes

回答

0

我覺得你的問題是查詢裏面你有正則表達式,而不是REGEXP:

http://dev.mysql.com/doc/refman/5.1/en/regexp.html

所以你的代碼應該是這樣的:

dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEXP \'P9W(38|40|50)\' ')) 
dbGetQuery(con, paste0(' select * from Mydata where [ID] REGEXP \'P9W(38|40|50)(_1){,1}\' ')) 

給一些反饋請,我不對數據庫工作不大,但我認爲這將解決您的問題

+0

朋友!我已經嘗試了兩種(請參閱我的問題...'REGEX'(或'REGEXP'))...沒有成功 –