SQL Queries from inside R

In your life as a data scientist, you'll often be working with huge databases that contain tables with millions of rows. If you want to do some analyses on this data, it's possible that you only need a fraction of this data. In this case, it's a good idea to send SQL queries to your database, and only import the data you actually need into R.

dbGetQuery()?is what you need. As usual, you first pass the connection object to it. The second argument is an SQL query in the form of a character string. This example selects theagevariable from thepeopledataset where gender equals "male":

dbGetQuery(con, "SELECT age FROM people WHERE gender = 'male'")

Apart from checking equality, you can also check forless thanandgreater thanrelationships, with, just like in R.

# Connect to the database

library(DBI)

con <- dbConnect(RMySQL::MySQL(),

dbname = "tweater",

host = "courses.csrrinzqubik.us-east-1.rds.amazonaws.com",

port = 3306,

user = "student",

password = "datacamp")

# Import post column of tweats where date is higher than '2015-09-21': latest

latest<-dbGetQuery(con,"select post from tweats where date>'2015-09-21'")

# Print latest

latest

# Create data frame specific

specific<-dbGetQuery(con,"select message from comments where tweat_id=77 and user_id>4")

# Print specific

specific

There are also dedicated SQL functions that you can use in theWHEREclause of an SQL query. For example,CHAR_LENGTH() returns the number of characters in a string.


Of course, SQL does not stop with the the three keywordsSELECT,FROMandWHERE. Another very often used keyword isJOIN, and more specificallyINNER JOIN. Take this call for example:

SELECT name, post

FROM users INNER JOIN tweats on users.id = user_id

WHERE date > "2015-09-19"

Here, theuserstable is joined with thetweatstable. This is possible because theidcolumn in theuserstable corresponds to theuser_idcolumn in thetweatstable. Also notice howname, from theuserstable, andpostanddate, from thetweatstable, can be referenced to without problems.

Can you predict the outcome of the following query?

SELECT post, message

FROM tweats INNER JOIN comments on tweats.id = tweat_id

WHERE tweat_id = 77


You've used?dbGetQuery()?multiple times now. This is a virtual function from the DBI package, but is actually implemented by the RMySQL package. Behind the scenes, the following steps are performed:

Sending the specified query with?dbSendQuery();

Fetching the result of executing the query on the database with?dbFetch();

Clearing the result with?dbClearResult().

# Send query to the database

res <- dbSendQuery(con, "SELECT * FROM comments WHERE user_id > 4")

# Use dbFetch() twice

dbFetch(res, n = 2)

dbFetch(res)

# Clear res

dbClearResult(res)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市惹资,隨后出現(xiàn)的幾起案子侮措,更是在濱河造成了極大的恐慌畏吓,老刑警劉巖列赎,帶你破解...
    沈念sama閱讀 211,123評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件臼氨,死亡現(xiàn)場離奇詭異持隧,居然都是意外死亡褥实,警方通過查閱死者的電腦和手機僻澎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評論 2 384
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事弟灼⊙谇” “怎么了涮帘?”我有些...
    開封第一講書人閱讀 156,723評論 0 345
  • 文/不壞的土叔 我叫張陵妇多,是天一觀的道長咸包。 經(jīng)常有香客問我坟比,道長籍琳,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,357評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,412評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著究珊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,760評論 1 289
  • 那天,我揣著相機與錄音臣缀,去河邊找鬼脂倦。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 38,904評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼秽五!你這毒婦竟也來了洲胖?” 一聲冷哼從身側(cè)響起腐晾,我...
    開封第一講書人閱讀 37,672評論 0 266
  • 序言:老撾萬榮一對情侶失蹤淹冰,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后牺勾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體驻民,經(jīng)...
    沈念sama閱讀 44,118評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,456評論 2 325
  • 正文 我和宋清朗相戀三年糙捺,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坏快。...
    茶點故事閱讀 38,599評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡饮焦,死狀恐怖县踢,靈堂內(nèi)的尸體忽然破棺而出械哟,到底是詐尸還是另有隱情,我是刑警寧澤殿雪,帶...
    沈念sama閱讀 34,264評論 4 328
  • 正文 年R本政府宣布,位于F島的核電站锋爪,受9級特大地震影響丙曙,放射性物質(zhì)發(fā)生泄漏爸业。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,857評論 3 312
  • 文/蒙蒙 一亏镰、第九天 我趴在偏房一處隱蔽的房頂上張望扯旷。 院中可真熱鬧,春花似錦索抓、人聲如沸钧忽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽耸黑。三九已至,卻和暖如春篮幢,著一層夾襖步出監(jiān)牢的瞬間大刊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評論 1 264
  • 我被黑心中介騙來泰國打工三椿, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留缺菌,地道東北人。 一個月前我還...
    沈念sama閱讀 46,286評論 2 360
  • 正文 我出身青樓搜锰,卻偏偏與公主長得像伴郁,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蛋叼,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,465評論 2 348

推薦閱讀更多精彩內(nèi)容