我正在使用postgresql。
假設我有這個表名my_table:
id | idcm | stores | du | au | dtc |
----------------------------------------------------------------------------------
1 | 20447 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799 01 |
2 | 20456 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799 01 |
3 | 20478 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799 01 |
4 | 20482 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799 01 |
5 | 20485 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996 02 |
6 | 20497 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996 02 |
7 | 20499 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996 02 |
我只想選擇值id等于stores(該行的)陣列元素之一的行。
但是,型別stores不是陣列,是jsonb。
所以我想得到這樣的東西:
id | idcm | stores | du | au | dtc |
----------------------------------------------------------------------------------
2 | 20456 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799 01 |
5 | 20485 | [7, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996 02 |
6 | 20497 | [2, 6] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996 02 |
7 | 20499 | [5, 7] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996 02 |
我試過了
select * from my_table where stores::text ilike id::text;
但它回傳零行,因為我需要在%之前和之后放置通配符id,
所以我嘗試過
select * from my_table where stores::text ilike %id%::text;
但我得到一個語法錯誤。
uj5u.com熱心網友回復:
將 ID 轉換為單個 JSON 值后,您可以使用contains 運算子:
select *
from the_table
where stores @> to_jsonb(id)
uj5u.com熱心網友回復:
嘗試這個:
select * from my_table where id = any(stores);
uj5u.com熱心網友回復:
樣本 :
create table stores_table (id serial, stores jsonb);
然后添加樣本值:
insert into stores_table (stores) values ('[2,5]'), ('[2, 5]'), ('[2,6]'), ('[4,7]');
搜索包含 id 的商店:
select * from stores_table where stores @> to_jsonb(id);
你會得到 :
id | stores
--- --------
2 | [2, 5]
4 | [4, 7]
(2 rows)
希望這有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526530.html
