Firebase INNER JOIN和GROUP BY月份查询

时间:2017-07-06 02:17:26

标签: mysql firebase firebase-realtime-database nosql

我在Firebase中设计数据库结构时遇到了一些困难。我是新手,所以我还不熟悉它。

enter image description here

交易表将记录日期以及所有子类别的总金额。对于每个子类别表,它只会根据其类型记录相关数据。

我试图做的是,无论如何,按月计算每个用户组的某个子类别的总金额?在MySQL中,我可以简单地INNER JOIN, WHERE clause and GROUP BY date,但我不确定这种设计结构,是否可以这样做?或者我应该修改结构?

输出应该类似于我选择food transaction

Month: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
Amount : 0, 0, 0, 0, 0, 0, 25, 0, 0, 0, 0, 0

1 个答案:

答案 0 :(得分:1)

尝试在像Firebase这样的NoSQL数据库中建模SQL表结构是一种痛苦的方法。不要再考虑内部联接和分组子句等SQL概念了。

取而代之的是您正在使用的平台的本质。例如:您是否需要经常显示帐户的交易清单?如果是这样,为什么不在JSON树中对其进行建模:

accountTransactions
  accountId1
    transaction1: {
      type: "entertainment"
      ...
    }
    transaction2: {
      type: "food"
      ...
    }
  accountId2
    transaction3: {
      type: "food"
      ...
    }
    transaction4: {
      type: "food"
      ...
    }

现在,如果您想要帐户1的交易列表,而不是需要查询,则可以直接从/accountTransactions/accountId1开始。

如果您还想要其他事务列表,则可能需要复制树中的某些数据。例如,如果要显示所有食品交易的列表,可以将其添加到数据库中:

transactionPathsByType
  food
    transaction2: "/accountTransactions/accountId1/transaction2"
    transaction3: "/accountTransactions/accountId2/transaction3"
    transaction4: "/accountTransactions/accountId2/transaction4"

有很多方法可以模拟这种最后的关系。例如,您还可以将事务列表保留为单个平面列表:

accountTransactions
    transaction1: {
      account: "accountId1"
      type: "entertainment"
      ...
    }
    transaction2: {
      account: "accountId2"
      type: "food"
      ...
    }
    transaction3: {
      account: "accountId2"
      type: "food"
      ...
    }
    transaction4: {
      account: "accountId2"
      type: "food"
      ...
    }

这将简化从事务类型到事务的映射到:

transactionIdsByType
  food
    transaction2: true
    transaction3: true
    transaction4: true

我们在这里只使用true作为虚拟值,因为查找每个事务所需的所有信息都已存在于密钥中。

如果您使用直接交易列表也想要快速查找帐户的交易ID,则可以添加将帐户ID映射到相应交易ID的索引:

transactionIDsByAccount
  accountId1
    transaction1: true
    transaction2: true
  accountId2
    transaction3: true
    transaction4: true

有很多可能的模型,因为有app的想法。更可能的。有关好的介绍文章,我建议您阅读NoSQL data modeling。绝对也可以在youtube上观看Firebase for SQL developers

相关问题