Ruby on Rails - 将数据库查询限制为仅一个结果
Ruby on Rails - Limit Database Query to One Result only
我想查询数据库,但只知道是否至少有一个结果。我试图将这笔交易的成本降到最低。 Rails 中的结构如何使查询成为 SQL 中的 SELECT TOP
或 SELECT FIRST
?
你可以试试exists?
Person.exists?(5) # by primary key
Person.exists?(name: 'David')
Person.exists? # is there at least one row in the table?
Person.where(name: 'Spartacus', rating: 4).exists?
Person.active.exists? # if you have an "active" scope
请注意,这将 SQL 查询中的结果集限制为 1,并且 select 子句类似于 SELECT 1 AS one
我想查询数据库,但只知道是否至少有一个结果。我试图将这笔交易的成本降到最低。 Rails 中的结构如何使查询成为 SQL 中的 SELECT TOP
或 SELECT FIRST
?
你可以试试exists?
Person.exists?(5) # by primary key
Person.exists?(name: 'David')
Person.exists? # is there at least one row in the table?
Person.where(name: 'Spartacus', rating: 4).exists?
Person.active.exists? # if you have an "active" scope
请注意,这将 SQL 查询中的结果集限制为 1,并且 select 子句类似于 SELECT 1 AS one