Tengo la tabla batch_table , que contiene el tipo de ID de batchid de serial int y el tipo de data de JSONB, indexé la columna data usando GIN ,
batchid | data --------------------------------------------- 1 | [{"year":2000,"productid":[21, 32, 5]}] 2 | [{"year":2001,"productid":[21, 39, 5]},{"year":2000,"productid":[1, 25, 5]}] 3 | NULL 4. | [{"year": 2000,"productid":[5]} Ahora quiero obtener batchid usando los siguientes requisitos
1. year = 2000 & productid = 5
2. year = 2000 & productid = (21 o 5)
3. year = 2000 & productid = (21 & 5)
y probé esto
SELECT batchid FROM batch_table WHERE (data->>'year')::int = 2000 AND (data->>'productid')::int = 5; con AND & OR para otras consultas
Puede usar el operador de contención @> para buscar en jsonb (esto incluso puede usar su índice):
1.
select * from batch_table where data @> '[{"year":2000,"productid":[5]}]';2.
select * from batch_table where data @> '[{"year":2000,"productid":[21]}]' or data @> '[{"year":2000,"productid":[5]}]';3.
Dependiendo de sus necesidades, puede utilizar uno de estos:
Estos seleccionarán filas, donde el año = 2000 con productid = 21 están en el mismo objeto y el año = 2000 con productid = 5 están en el mismo objeto (pero estos objetos pueden ser diferentes).
select * from batch_table where data @> '[{"year":2000,"productid":[21]}]' and data @> '[{"year":2000,"productid":[5]}]'; select * from batch_table where data @> '[{"year":2000,"productid":[21]},{"year":2000,"productid":[5]}]';Esto seleccionará filas, donde el año = 2000 con productid = 21 están en el mismo objeto , así como productid = 5
select * from batch_table where data @> '[{"year":2000,"productid":[21, 5]}]';