我試圖選擇用戶回覆的所有最近的討論。但以下查詢不起作用。返回0個條目。我是sql新手,我想我在使用「IN」時出現了問題。請幫助故障排除這樣的:SQLite查詢問題
SELECT * FROM discussions
WHERE discussable_id IN
(SELECT commentable_id FROM comments
WHERE commentable_type = 'Discussion' AND user_id = 1);
也是,如果我想作爲排序依據的comment.created_at上述查詢什麼?我怎麼做?此外,如果我還想包括用戶創建的所有討論,並且按最新活動對所有查詢進行排序(可能是discussion.created_at或comment.created_at),該怎麼辦?順便說一句,我在軌道上。我一直試圖解決這個問題幾個小時。真的很感激任何輸入。非常感謝!
UPDATE2:看起來我應該在查詢中用「id」替換discussable_id,你發現了嗎? :)這樣一個乏味的問題。現在,我如何訂購由comment.created_at返回的討論?我應該打開另一個問題嗎?
UPDATE1: 對不起,這裏是ActiveRecord的:
# 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項。謝謝!
ActiveRecord在哪裏? – 2011-04-17 16:10:40
是dicussable_id和commentable_id有關係嗎?請張貼討論和意見表的結構。還提到它們是如何相關的? – Ravin 2011-04-17 16:18:13