【问题标题】:Run MySQL Query through all tables in R通过 R 中的所有表运行 MySQL 查询
【发布时间】:2023-03-31 20:00:01
【问题描述】:

我正在尝试生成类似于此的图表:

来自具有许多表的数据库(作为 x 轴)。

数据:

我在数据库中有几个表如下:Table1, Table2, Table3, etc每个表有 500+ 行和 10+ 列(属性)

问题

其中一列包含该消息的条件(一般、良好、非常好等)。

在数据库中返回这个的查询:

SELECT message_condition Condition,
COUNT(message_id) NumMessage
FROM `table1` GROUP message_condition

这将返回:

------------------------
Condition |  NumMessage
------------------------
          |  80 
Fair      |  20
Good      |  60
Ideal     |  50
Great     |  80

更新:总是有 4 个条件和一个空条件(对于没有条件的消息)。因此,如果我对所有表运行查询,我将得到与上面相同的表,但数字不同。

现在,我想将这些查询应用到数据库中的所有表,这样我就可以生成上面的图表(以表为 x 轴)。

我试过用这个方法:

doCountQuerys <- function(con, table) {
    query <- paste('
        SELECT message_condition Condition,
        COUNT(message_id) NumMessage FROM`', table, '` GROUP message_condition', sep = '')
    ts     <- dbGetQuery(con, query)
    return(ts)
}

lists <- dbListTables(con)  # get list of all tables in the database

countz <- numeric(0)       # store the counts for all tables

for (i in 1:length(list)) {
    counta <- doCountQuerys(con, lists[i])
    countz[i] <- counta[[1]]
    #print(countz[[1]])
}

但我收到此错误:

## Warning in countz[i] <- counta[[1]]: number of items to replace is not a
## multiple of replacement length

我不认为我这样做是正确的,知道如何在 R 中的所有表中运行该查询并生成该图吗?

【问题讨论】:

  • 您的查询是否会为数据库中的每个表生成相同数量的消息条件及其计数?
  • @TimBiegeleisen 不,每个表的每个条件的消息计数都不同。例如table1,公平条件的NumMessage为20,而table2,公平条件的NumMessage为80。并且总是有4个条件为空。

标签: mysql r


【解决方案1】:

一些提示。

首先,您需要在数据框中包含表名,以便在绘图期间按此分组。最简单的方法是将其作为常量添加到您的查询中,这样它就变成了

SELECT 'table1' TableName, etc etc

只需 paste 将其添加到函数中的现有查询中即可:

query <-    paste0("SELECT '", table,"' TableName, COALESCE(NULLIF(message_condition, ''), 'default') message_condition, COUNT(message_id) NumMessage FROM '", table, "' GROUP BY message_condition",   sep = '')

您还应该为条件为空时添加默认类别名称。您可以使用COALESCEISNULL 执行此操作,如图所示。

编辑 考虑一下,您只需将 rbind 每个结果设置到 for 循环中整个数据框的末尾即可。 R - Concatenate two dataframes?

(顺便说一句,通常使用 apply 而不是 for 循环)

类似(未经测试...):

df <- data.frame(TableName=character(), message_condition=character(), NumMessage=integer())
for (i in 1:length(lists)) {
  rbind(df, doCountQuerys(con, lists[i]))
}

所以,你最终应该得到一个看起来像这样的数据框:

TableName, message_condition, NumMessage
table1, default, 30
table1, fair, 20
table1, good, 60
table1, ideal, 50
table2, default, 15
table2, fair, 10
table2, good, 30
table2, ideal, 60
table3, default, 10
table3, fair, 5
table3, good, 25
table3, ideal, 40

你可以简单地绘制这个:

ggplot(df, aes(x=TableName, y=NumMessage, fill=message_condition)) + geom_bar(stat="identity")

希望这对您有所帮助,这就是您所追求的

【讨论】:

  • 是的,问题是循环不起作用:(如果我将SELECT 'table1'添加到查询中,所有表不都是一样的吗?
  • 已编辑 - 您的循环可以替换为单个 rbind 并添加完整查询
  • 问题是我刚开始学习/使用 R,但我不知道如何使用 rbind
  • mysql查询选择表名好像是列,我的数据集中没有表名的列
  • 你将它传递给你的函数,所以它来自某个地方,不是吗?
猜你喜欢
  • 2017-10-29
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多