google-app-engine - 在 Google App Engine 上,我如何在 GQL 中查找客户的最新订单?

标签 google-app-engine join gql

如果我有两个表,Customers 和 Orders,我想查找客户的最新订单,我该如何使用 GQL 在 Google App Engine 上执行此操作?

通常,我会通过订单表中存在的外键 customer_id 连接这两个表。

select orders.* from customers, orders 
where customers.customer_id = orders.customer_id
and orders.order_id = (select top 1 sub_orders.order_id from orders sub_orders 
                where sub_orders.customer_id = orders.customer_id 
                order by sub_orders.order_date desc)

但是,由于在 Google App Engine 上似乎无法进行联接,因此我不确定如何解决此限制。如有任何建议,我们将不胜感激。

最佳答案

Google App Engine 中的 DataStore 与关系数据库确实有很大不同。有一些相似之处,但在设计数据模型时了解不同之处很重要。

通常定义这种关系的方式是使用引用属性:

class Customer(db.Model):
    name = db.StringProperty()

class Order(db.Model):
   customer = db.ReferenceProperty( Customer,
                                    collection_name = 'orders' )

Order 实体定义中的 ReferenceProperty 导致在 Customer 实体中创建一个名为“orders”的属性,这样如果“customer”是一个 Customer 实例,您可以通过引用“customer”找到所有订单。命令'。

例如:

customer = Customer.gql("WHERE name = :1", "Bob")[0] # Returns the first customer named Bob
order1 = customer.orders[0]
order2 = customer.orders.order("date")[0] # Sorts the Orders by date and gets the first one

引用属性已记录 here.

另一个需要理解的重要概念是实体组的概念。实体组中的实体存储在同一个节点上,因此可以更有效地存储和检索它们。它们对于使用事务也至关重要。

关于google-app-engine - 在 Google App Engine 上,我如何在 GQL 中查找客户的最新订单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/902516/

相关文章:

python - 谷歌应用引擎 : Determine whether Current Request is a Taskqueue

node.js - 从部署在谷歌云应用程序引擎中的 Node js应用程序查询时,云SQL抛出ETIMEDOUT错误

mysql - WordPressMU - 获取博客列表,按博客名称字母顺序排序

java - 在 GQL 过滤器中使用列表

python - 本地主机上的 Google App Engine GQL 查询

google-cloud-datastore - 嵌入式实体上的 GQL 投影查询

python - 如何保护我在应用程序内进行的 REST 调用?

java - App-Engine (Java) 文件上传

mysql - 加入两个表而不返回不需要的行

mysql - Rails/MySQL 查询,其中第三级连接 ID 不存在