5

我在rails中使用这个查询

这里: @album_ids,@country_ids是数组

@audios= Audio.where({:album_id => @album_ids, :country_id => @country_ids})
It produces following SQL:

 Audio Load (0.3ms)  SELECT `audios`.* FROM `audios` WHERE `audios`.`album_id` IN (1, 2) AND `audios`.`country_id` IN (1, 2)

但我希望查询生成为:

 Audio Load (0.3ms)  SELECT `audios`.* FROM `audios` WHERE `audios`.`album_id` IN (1, 2) OR `audios`.`country_id` IN (1, 2) 

OR而不是AND

提前致谢

4

3 回答 3

7

对于 Rails 3(使用 AREL),

at = Audio.arel_table
audios = Audio.where(at[:album_id].in(@album_ids).or(at[:country_id].in(@country_ids)))

# Audio Load (0.3ms)  SELECT `audios`.* FROM `audios` WHERE ((`audios`.`album_id` IN (1, 2) OR `audios`.`country_id` IN (1, 2)))
于 2012-08-16T07:49:25.507 回答
0

Where 子句将始终创建一个 AND,或者将其更改为 2 行:

@audios  = Audio.where({:album_id => @album_ids})
@audios += Audio.where({:country_id => @country_ids})

因为 rails3 不调用内联搜索,而是编译查询,它应该将其作为一个查询执行。

或者:

@audios= Audio.where(["album_id IN (?) OR country_id IN (?)", @album_ids, @country_ids])
于 2012-08-16T07:39:04.193 回答
0

试试这个方法

a = Report.scoped
a.where(
  a.table[:id].in([1,2,3])
    .or( 
      a.table[:model_id].in([3,4,5])
    )
  ).to_sql
=> "SELECT `reports`.* FROM `reports`  WHERE ((`reports`.`id` IN (1, 2, 3) OR `reports`.`model_id` IN (3, 4, 5)))" 
于 2012-08-16T07:43:44.900 回答