Rails 不同的查询
Rails query with distinct
我很难弄清楚如何正确查询我的数据库。
我的查询如下:
@events = Event.where("startdate > '#{now}'")
事件模型中有一列名为 name
,我需要 return 所有 name
不同的事件,但我还需要所有列。我将如何做到这一点?
我认为这会奏效,但事实并非如此:
@events = Event.where("startdate > '#{now}'").uniq
然后我发现它不知道看什么来判断唯一性,我怎么告诉unique看name栏来判断唯一性?
数据:
ID | Name | Description | start
1 christmas holiday 12-25-16
2 christmas holiday 12-25-17
3 thanksgiving holiday 11-24-16
应该return
1 christmas holiday 12-25-16
3 thanksgiving holiday 11-24-16
谢谢,
你可以用积木告诉uniq
如何做这项工作
@events = Event.where("startdate > '#{now}'").uniq(&:name)
否则,也许这样更好,您可以在 SQL 中完成所有操作,因为
uniq
不是,它会迭代您的结果集。
@events = Event.where("startdate > '#{now}'").group(:name)
您可以通过以下方式查询 运行:
@event = Event.where("startdate > '#{now}'").uniq(:name)
这将能够为您提供只有唯一条目的数据。
我很难弄清楚如何正确查询我的数据库。
我的查询如下:
@events = Event.where("startdate > '#{now}'")
事件模型中有一列名为 name
,我需要 return 所有 name
不同的事件,但我还需要所有列。我将如何做到这一点?
我认为这会奏效,但事实并非如此:
@events = Event.where("startdate > '#{now}'").uniq
然后我发现它不知道看什么来判断唯一性,我怎么告诉unique看name栏来判断唯一性?
数据:
ID | Name | Description | start
1 christmas holiday 12-25-16
2 christmas holiday 12-25-17
3 thanksgiving holiday 11-24-16
应该return
1 christmas holiday 12-25-16
3 thanksgiving holiday 11-24-16
谢谢,
你可以用积木告诉uniq
如何做这项工作
@events = Event.where("startdate > '#{now}'").uniq(&:name)
否则,也许这样更好,您可以在 SQL 中完成所有操作,因为
uniq
不是,它会迭代您的结果集。
@events = Event.where("startdate > '#{now}'").group(:name)
您可以通过以下方式查询 运行:
@event = Event.where("startdate > '#{now}'").uniq(:name)
这将能够为您提供只有唯一条目的数据。