2017-08-04 63 views
0

在带有Postgres数据库的Rails 5应用程序中,我有一个型号为Postjsonb列,名称为commentscomments的默认值是{}在Rails 5和PostgreSQL中查询jsonb列的完全匹配

我想返回默认值为comments的计数posts

当我运行​​时,我得到了Post表中每条记录的计数。

是否有只会返回完全匹配的查询,所以我可以知道没有评论的posts的数量?

回答

0

在带有Postgres数据库的我的Rails 5应用程序中,我有一个名为comments的jsonb列的模型Post。评论的默认值是{}。

比方说,这是你的表:

CREATE TABLE Posts 
(
    post_id SERIAL PRIMARY KEY, 
    comments jsonb DEFAULT '{}' /* or json instead of jsonb */ 
) ; 

...一些示例数据

INSERT INTO Posts 
    (comments) 
VALUES 
    ('{"something": "a comment"}'), 
    ('[{"something": "a comment"}, {"something":"another comment"}]'), 
    (DEFAULT), 
    ('{}'), 
    (DEFAULT), 
    (NULL) ; 

...看起来像:

SELECT * FROM Posts; 
 
post_id | comments              
------: | :------------------------------------------------------------- 
     1 | {"something": "a comment"}          
     2 | [{"something": "a comment"}, {"something": "another comment"}] 
     3 | {}                
     4 | {}                
     5 | {}                
     6 | null               

我想返回具有评论默认值的帖子的数量。

这是因为comments列(平等)与{}比较简单:

SELECT 
    count(*) 
FROM 
    posts 
WHERE 
    comments = '{}' /* or '{}'::jsonb */ 
 
| count | 
| ----: | 
|  3 | 

dbfiddle here


(我有没有试过)是你把它翻译成轨道:

Post.where("comments = ?", {}.to_json).count 
相关问题