【问题标题】:Object.merge creates AND in SQL query- what method creates OR?Object.merge 在 SQL 查询中创建 AND - 什么方法创建 OR?
【发布时间】:2015-01-30 11:12:34
【问题描述】:

以下代码使用合并生成以下 SQL。我已经用粗体标出了要更改的运算符。

   Micropost.from_users_followed_by(self).merge(
    Micropost.direct_replies_to(self))

SELECT "microposts".* FROM "microposts" WHERE "microposts"."reply_to" = 'example-1' AND (user_id IN (SELECT follow_id FROM 关系 WHERE follower_id = 2) AND user_id = 2) ORDER BY microposts.created_at DESC

什么方法会在两者之间产生 OR 运算符?即:

SELECT "microposts".* FROM "microposts" WHERE "microposts"."reply_to" = 'example-1' OR (user_id IN (SELECT follow_id FROM 关系 WHERE follower_id = 2) AND user_id = 2) ORDER BY microposts.created_at DESC

【问题讨论】:

    标签: sql ruby-on-rails


    【解决方案1】:

    对一列的值进行 OR 运算符,您可以将数组传递给 Where 子句,并使用 ActiveRecord 使用 IN(value1,value2):

    一栏 Micropost.where(:reply_to => ["value1", "value2"])

    更多专栏 Micropost.where("reply_to = ? or follower_id = ?", 'example-1', 2)

    或者试试这个

    Micropost.where("(reply_to = 'example-1') or (another_condition))

    【讨论】:

    • 你也可以使用Micropost.from_users_followed_by(self) || Micropost.direct_replies_to(self)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    相关资源
    最近更新 更多