【问题标题】:Rails query with distinct具有不同的 Rails 查询
【发布时间】:2017-06-01 17:51:55
【问题描述】:

我很难弄清楚如何正确查询我的数据库。

我的查询如下:

@events = Event.where("startdate > '#{now}'")

事件模型中有一个名为name 的列,我需要返回所有name 不同的事件,但我还需要所有列。我将如何做到这一点?

我认为这会起作用,但事实并非如此:

@events = Event.where("startdate > '#{now}'").uniq

然后我意识到它不知道看什么来判断唯一性,我如何告诉唯一性看名称列来判断唯一性?

数据:

ID | Name         | Description  | start
1    christmas      holiday        12-25-16
2    christmas      holiday        12-25-17  
3    thanksgiving   holiday        11-24-16

应该返回

1    christmas      holiday        12-25-16
3    thanksgiving   holiday        11-24-16

谢谢,

【问题讨论】:

  • “谁的名字与众不同”是什么意思?如果有更多同名事件,只有一个事件?这是正确的吗?
  • 已编辑,是的,有一列名为“name”
  • 那么,在这种情况下,同名事件中的一个随机事件?
  • @Ursus 见编辑。谢谢

标签: mysql ruby ruby-on-rails-5.1


【解决方案1】:

你可以用一个块告诉uniq如何工作

@events = Event.where("startdate > '#{now}'").uniq(&:name)

否则,这可能更好,您可以在 SQL 中完成所有操作,因为 uniq 不是,它会迭代您的结果集。

@events = Event.where("startdate > '#{now}'").group(:name)

【讨论】:

  • 我的荣幸先生
【解决方案2】:

您可以通过以下方式运行查询:

@event = Event.where("startdate > '#{now}'").uniq(:name)

这将能够为您提供只有唯一条目的数据。

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多