2011-06-01 48 views
2

我有3种表&型号: 品牌 brand_data_records 和 brand_data_records_brands - 连接表rails和sql其中IS NOT NULL无法正常使用连接。 Rails的2.3.5和Ruby 1.8.7 - MySQL的5

在铁轨我想对于一个给定的日期范围内的所有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

您可能是指引用列:

`sentiment` IS NOT NULL 

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

+0

我尝试了符号的方法和MySQL是:SELECT情绪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和date_retrieved> ='2011-05-02'AND date_retrieved <='2011-06-01'and'---:sentiment \ n'IS NOT NULL),并且具有相同的问题。我确实在sql字符串中尝试了硬编码的情绪,并且工作正常,所以你正处于问题的正确轨道上... – Joelio 2011-06-01 21:36:58

+0

如果我让情绪成为符号并执行此操作:matching_records = BrandDataRecord.find(:all,:select = > column_match,:joins =>:brands,:conditions => [“brand_data_records_brands.brand_id =?and date_retrieved> =?AND date_retrieved <=?and#{column_match} IS NOT NULL”,brand.id,start_date,end_date]) 然后它工作。这看起来很丑陋,但至少可以工作! – Joelio 2011-06-01 21:38:29

+0

是的,我的意思是“一个字符串永远不会是NULL”,而不是永远不会。 – tadman 2011-06-02 15:54:38

相关问题