如果我有两个表,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/