如何编写像 SQL 的 SELECT x FROM 这样的查询

发布于 2024-12-23 07:06:30 字数 295 浏览 4 评论 0原文

我想编写一个执行类似以下 SQL 查询的查询:

SELECT name FROM contacts WHERE blah blah

我知道我可以执行类似以下操作:

for contact in Contacts.gql(WHERE_CLAUSE, args).fetch(1000):
  print contact.name

但有没有办法直接从查询中获取 name 而不必循环结果?它会在性能方面提供任何优势吗?

I want to write a query that does something like this SQL query:

SELECT name FROM contacts WHERE blah blah

I know I can do something like this:

for contact in Contacts.gql(WHERE_CLAUSE, args).fetch(1000):
  print contact.name

but isn't there a way to get name directly from a query without having to loop on the results? would it provide any advantage in performance?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

远山浅 2024-12-30 07:06:31

没有。做不到。

GQL 查询返回所请求的零个或多个实体或键
种类。每个 GQL 查询始终以 SELECT * 或 SELECT 开头
。 (GQL 查询无法执行类似 SQL 的“连接”查询。)

http ://code.google.com/appengine/docs/python/datastore/gqlreference.html

但是您可以创建一个简单的包装器来为您完成此操作。类似于:

def get_all_of_field(model, field):
  for x in model.all():
    yield getattr(x, field)

names = get_all_of_field(Contact, 'name')

性能无法通过这种方式提高,因为无论如何 API 都会读取整个“行”。您要么阅读整个“行”,要么只阅读其关键字。

Nope. Can't be done.

A GQL query returns zero or more entities or Keys of the requested
kind. Every GQL query always begins with either SELECT * or SELECT
key. (A GQL query cannot perform a SQL-like "join" query.)

http://code.google.com/appengine/docs/python/datastore/gqlreference.html

But you can create a simple wrapper to do it for you. Something like:

def get_all_of_field(model, field):
  for x in model.all():
    yield getattr(x, field)

names = get_all_of_field(Contact, 'name')

Performance can't be improved that way as the entire "line" is read by the API no matter what. Either you read the entire "line" or just its key.

壹場煙雨 2024-12-30 07:06:31

您现在可以使用投影查询来执行此操作。对于数据库,请参阅此处的文档:

https://developers.google.com/appengine /docs/python/datastore/projectionqueries

对于 ndb,请参阅此处的文档:

https://developers.google.com/appengine/docs/python/ndb/queries#projection

You can do this now using Projection queries. For db, see the documentation here:

https://developers.google.com/appengine/docs/python/datastore/projectionqueries

For ndb, see the documentation here:

https://developers.google.com/appengine/docs/python/ndb/queries#projection

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文