Rails3 NOT IN查询将字符串作为值

时间:2013-05-03 13:39:08

标签: mysql ruby-on-rails

我正在尝试选择论坛列表中没有帖子的用户。为此,我写了一个像这样的查询

users_id = Post.where(:forum_id => 1).collect { |c| c.user_id }
@users = User.where('topic_id = ? and id not in ? ', "#{@topic.id}", "#{users_id}")

此代码抛出mysql错误,并在我的日志中

SELECT `user`.* FROM `user` WHERE (forum_id = '2222' and id not in '[5877, 5899, 5828, 5876, 5841, 5838, 5840, 5882, 5881, 5870, 5842, 5843, 5844, 5845, 5889, 5896, 5869, 5847, 5849, 5850, 5855, 5857, 5859, 5867, 5861, 5863, 5865, 5868, 5829, 5830, 5831, 5832, 5833, 5900, 6326, 6326, 6332, 5898, 6333, 6334, 6335, 6336, 6339, 7034, 7019, 6336, 5887, 5827, 9940, 9943, 9949, 7030, 9979, 9980, 5892, 9896, 14208, 14224, 14281, 14282, 14283, 5894, 5895, 14689, 14717]'

在mysql中,我执行以下查询,得到了预期的结果

select * from users where topic_id = 1 and id not in (select users_id from posts where forum_id = 1);

以上在rails中的查询似乎不起作用..

1 个答案:

答案 0 :(得分:2)

试试这个:

users_ids = Post.where(:forum_id => 1).collect { |c| c.user_id }
@users = User.where('topic_id = ? and id not in (?) ', @topic.id, users_ids)

另外,我建议你做一些改变:

  • 使用pluck而不是collect(pluck在数据库级别上)(pluck doc; pluck vs. collect

    users_ids = Post.where(:forum_id => 1).pluck(:user_id)

  • 在where子句中命名表以避免模糊调用(例如在链接中):

    User.where('users.topic_id = ? AND users.id NOT IN (?)', @topic.id, users_ids)

最终代码:

users_ids = Post.where(:forum_id => 1).pluck(:user_id)
@users = User.where('users.topic_id = ? AND users.id NOT IN (?)', @topic.id, users_ids)