【问题标题】:How to add an AND condition to SQL query如何在 SQL 查询中添加 AND 条件
【发布时间】:2026-01-27 07:10:01
【问题描述】:

我正在尝试添加一个 AND 条件,其中active = true 也包含在 rails 内的 SQL 查询中。

Schema.rb

...
create_table 'relationships', force: :cascade do |t|
    t.integer  'follower_id'
    t.integer  'followed_id'
    t.datetime 'created_at',                 null: false
    t.datetime 'updated_at',                 null: false
    t.boolean  'active', default: true
    t.index ['followed_id'], name: 'index_relationships_on_followed_id'
    t.index %w[follower_id followed_id], name: 'index_relationships_on_follower_id_and_followed_id', unique: true
    t.index ['follower_id'], name: 'index_relationships_on_follower_id'
  end
...

user.rb

...
def feed
 following_ids = "SELECT followed_id FROM relationships
                  WHERE follower_id = :user_id AND active = true"
                     
  View.where("user_id IN (#{following_ids})
         OR user_id = :user_id", user_id: id).includes(:user)
 end
...

但是,添加AND active = TRUE 似乎无法将followed_idsfollower_id 拉为self 并且active 布尔值是true

【问题讨论】:

    标签: sql ruby-on-rails


    【解决方案1】:

    设法通过在查询中分配active 来解决它。

    ...
    def feed
     following_ids = "SELECT followed_id FROM relationships
                      WHERE follower_id = :user_id AND active = :active"
                         
      View.where("user_id IN (#{following_ids})
             OR user_id = :user_id", user_id: id, active: true).includes(:user)
     end
    ...
    

    【讨论】: