目前,對於使用不同的參數重複搜索,我有這樣的ActiveRecord查詢生成:大廈的ActiveRecord/SQL查詢
current_user.documents.order(:updated_at).reverse_order.includes(:groups,:rules)
現在,平時我釘在一個where
子句來此執行此搜索。但是,我現在需要通過jsonb字段搜索所有具有特定值值的行,如鍵值對中一樣。我已經能夠做一個類似的東西在我的SQL,這種語法(數據字段只會正好有兩個級別的嵌套):
SELECT
*
FROM
(SELECT
*
FROM
(SELECT
*
FROM
documents
) A,
jsonb_each(A.data)
) B,
jsonb_each_text(B.value) ASC C
WHERE
C.value = '30';
不過,我想利用當前的ActiveRecord搜索使這個查詢(其中包括組/規則急切加載)。
我與使用逗號,我的理解是一個隱含的加盟,這是明確連接之前執行的掙扎,所以當我嘗試這樣:
select * from documents B join (select * from jsonb_each(B.data)) as A on true;
ERROR: invalid reference to FROM-clause entry for table "b"
LINE 1: ...* from documents B join (select * from jsonb_each(B.data)) a...
^
HINT: There is an entry for table "b", but it cannot be referenced from this part of the query.
但我不不瞭解如何引用完成的「表」,即在創建聯接調用之前創建的ActiveRecord查詢,以及使用隱式聯接的逗號語法來工作。
另外,我是一個SQL業餘愛好者,所以如果你看到一些改進或其他方式來做到這一點,請告訴。
編輯:文件表的說明:
Table "public.documents"
Column | Type | Modifiers | Storage | Stats target | Description
------------+-----------------------------+--------------------------------------------------------+----------+--------------+-------------
id | integer | not null default nextval('documents_id_seq'::regclass) | plain | |
document_id | character varying | | extended | |
name | character varying | | extended | |
size | integer | | plain | |
last_updated| timestamp without time zone | | plain | |
user_id | integer | | plain | |
created_at | timestamp without time zone | | plain | |
updated_at | timestamp without time zone | | plain | |
kind | character varying | | extended | |
uid | character varying | | extended | |
access_token_id | integer | | plain | |
data | jsonb | not null default '{}'::jsonb | extended | |
指標: 「documents_pkey」 主鍵,B樹(ID) ```
樣品行,首先將匹配搜索'30'(數據是最後一個字段):
2104 | 24419693037 | LsitHandsBackwards.jpg | | | 1 | 2017-06-25 21:45:49.121686 | 2017-07-01 21:32:37.624184 | box | 221607127 | 15 | {"owner": {"born": "to make history", "price": 30}}
2177 | /all-drive/uml flows/typicaluseractivity.svg | TypicalUserActivity.svg | 12375 | 2014-08-11 02:21:14 | 1 | 2017-07-07 14:00:11.487455 | 2017-07-07 14:00:11.487455 | dropbox | 325694961 | 20 | {"owner": {}}
你可以發表你的表和一些樣本數據的定義嗎? – joanolo
@joanolo我添加了一些信息。我也可以發佈小組/規則說明,但我認爲這不會有太大的幫助。 – abcde13
圖像很棒......但文字更好,因爲我們可以複製和播放它。 – joanolo