rails和sql,其中IS NOT NULL与join无法正常工作。 Rails 2.3.5和Ruby 1.8.7 - mysql 5

时间:2011-06-01 21:16:17

标签: sql ruby-on-rails inner-join

我有3张桌子和1张桌子。楷模: 品牌 brand_data_records 和 brand_data_records_brands - 联接表

在rails中,我希望给定品牌的给定日期范围内的所有brand_data_records,其中给定属性在数据库中不为空。

所以我有:

BrandDataRecord.find(:all, :select => column_match, :joins => :brands, :conditions => ["brand_data_records_brands.brand_id = ? and date_retrieved >= ? AND date_retrieved <= ? and ? IS NOT NULL",brand.id,start_date,end_date,column_match])

这会生成这个sql:

  SELECT sentiment FROM `brand_data_records` INNER JOIN `brand_data_records_brands` ON `brand_data_records_brands`.brand_data_record_id = `brand_data_records`.id INNER JOIN `brands` ON `brands`.id = `brand_data_records_brands`.brand_id WHERE (brand_data_records_brands.brand_id = 330516084 and date_retrieved >= '2011-05-02' AND date_retrieved <= '2011-06-01' and 'sentiment' IS NOT NULL) 

这通常有效,但它会返回一堆具有空值的额外记录。我认为它与连接有关,如果我用sql删除它只有它工作正常,但我不知道如何修复rails(甚至在sql中为此事实)

1 个答案:

答案 0 :(得分:1)

您可能想要引用该列:

 `sentiment` IS NOT NULL

你无意中做的是断言字符串'sentiment'不是空的,当然它永远不会是。在您的条件中传入:sentiment'sentiment'.to_sym'应该可以解决此问题,因为符号会在转换时使用反引号进行转义。