2014-08-31 67 views
0

我是Postgres的新手,我正在研究現有的Laravel應用程序。條目表使用名爲datahstore列。這是有問題的查詢:Postgres Aggregate Hstore

$query = \DB::table('entries') 
     ->where('f_id', '=', $f->id) 
     ->where('s_id', '=', \Config::get('s_id')) 
     ->select(\DB::raw('SUM(CAST("data"->\'total\' as decimal)) as "total"')) 
     ->get(); 

我可以看到他們在這裏做什麼,但這段代碼失敗,出現錯誤:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type numeric: \"\" (SQL: select SUM(CAST(\"data\"->'total' as decimal)) as \"total\" from \"entries\" where \"f_id\" = 70 and \"s_id\" = 1) 

我想不通爲什麼,任何人都可以解釋問題?

回答

2

使用NULLIF採取空字符串的護理:

'SUM(NULLIF("data"->\'total\', '')::numeric)) as "total"' 

可以使之NULL爲好,如果所有字段是NULL。

+0

我打算接受這個,因爲這實際上解決了我的問題。非常感謝 – outrunthewolf 2014-09-01 10:33:32

0

這裏的問題不是實際的查詢。

問題是「總計」條目是空的,當輸入到小數點時會導致錯誤。