2011-04-17 63 views
1

我試圖選擇用戶回覆的所有最近的討論。但以下查詢不起作用。返回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項。謝謝!

+0

ActiveRecord在哪裏? – 2011-04-17 16:10:40

+1

是dicussable_id和commentable_id有關係嗎?請張貼討論和意見表的結構。還提到它們是如何相關的? – Ravin 2011-04-17 16:18:13

回答

0

考慮:

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。)

快樂編碼。

+0

你可以嘗試'LEFT JOIN'而不是'JOIN'。 – 2011-04-17 18:01:10

+0

謝謝!我想出了爲什麼:看到UPDATE2,但現在我想通過comment.created_at命令進行討論。我應該打開另一個問題。 – randomor 2011-04-17 18:01:21

+0

我在這裏打開另一個問題,歡迎您提供幫助:http://stackoverflow.com/questions/5695459/sql-query-order-problem – randomor 2011-04-17 18:24:02