【问题标题】:SQLite query problemSQLite 查询问题
【发布时间】:2011-04-17 16:04:14
【问题描述】:

我正在尝试选择用户最近回复的所有讨论。但是下面的查询不起作用。返回 0 个条目。我是 sql 新手,我猜我使用“IN”时有问题。请帮助解决此问题:

    SELECT * FROM discussions 
    WHERE discussable_id IN 
    (SELECT commentable_id FROM comments 
    WHERE commentable_type = 'Discussion' AND user_id = 1);

另外,如果我想按comment.created_at 对上述查询进行排序怎么办?我怎么做?另外,如果我还想包含用户创建的所有讨论,并且还按最新活动(可以是讨论.created_at 或评论.created_at)对所有查询进行排序,该怎么办。顺便说一句,我在铁轨上。我一直在尝试解决这个问题几个小时。非常感谢任何输入。非常感谢!

UPDATE2:看起来我应该用“id”替换查询中的 Discussionable_id,你发现了吗? :) 这样一个乏味的问题。现在,如何通过comment.created_at 对返回的讨论进行排序?我应该打开另一个问题吗?

更新1: 抱歉,这里是活动记录:

# Table name: discussions
#
#  id               :integer         not null, primary key
#  title            :string(255)     not null
#  content          :text(255)       not null
#  created_at       :datetime
#  updated_at       :datetime
#  user_id          :integer
#  discussable_id   :integer
#  discussable_type :string(255)
class Discussion < ActiveRecord::Base
  has_many    :comments, :as => :commentable, :dependent => :destroy
  #this is the scope that I'm having trouble with:
  scope :user_replied_group_discussions, lambda {|user| replied_by(user) }

  def last_reply
    if self.comments.any?
      self.comments.last.created_at
    else
      self.created_at
    end
  end
  private
    def self.replied_by(user)
      discussion_ids = %(SELECT commentable_id FROM comments 
                     WHERE commentable_type = 'Discussion' AND user_id = :user_id)
      where("discussable_type = 'Group' AND discussable_id IN (#{discussion_ids}) ", 
           { :user_id => user })
    end
end

# Table name: comments
#
#  id               :integer         not null, primary key
#  content          :text
#  created_at       :datetime
#  updated_at       :datetime
#  commentable_id   :integer
#  commentable_type :string(255)
#  user_id          :integer
#

class Comment < ActiveRecord::Base

  belongs_to :commentable, :polymorphic => true
  belongs_to :user

end

无论如何,我尝试在 sqlite3 控制台中运行 sql 查询,返回 0 条目。谢谢!

【问题讨论】:

  • dicussable_id 和 commentable_id 是否相关?请张贴讨论结构和 cmets 表。并提及它们之间的关系?

标签: sql ruby-on-rails sqlite activerecord


【解决方案1】:

考虑:

SELECT d.* FROM discussions d
JOIN comments c
ON d.discussable_id = c.commentable_id
WHERE c.commentable_type = 'Discussion'
AND c.user_id = 1

这表明与IN 尝试建立的关系相同。如果返回零结果,那么这就是答案 ;-) 也许关系不符合预期? (d.discussable_id = c.commentable_id 似乎很奇怪。)

编码愉快。

【讨论】:

  • 你可以试试LEFT JOIN而不是JOIN
  • 谢谢!我已经弄清楚原因:请参阅 UPDATE2,但现在我想通过comment.created_at 订购讨论。我应该打开另一个问题。
  • 我这里又开了一个问题,欢迎大家帮忙:stackoverflow.com/questions/5695459/sql-query-order-problem
猜你喜欢
  • 2011-10-23
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 2013-02-05
  • 2015-09-27
  • 2011-01-07
相关资源
最近更新 更多