[英]How to get all values from one array which do not exist in another array?
[英]Postgres, get all items from one table which ids are not in another tables JSON array column?
我有两张桌子:
汽车表,其中包含:
id | name
1 | Audi
2 | Mercedes
3 | BMW
电动车
id | cars_id | non_valid_cars (json)
1 | 1 | [1,3]
2 | 3 | [1]
3 | 2 | [2,3]
如何 select 来自汽车表的所有记录,这些记录不在 Electric_cars 列中 ID 的 non_valid_cars 数组中,ID 为 cars_id?
另外,我正在使用 Laravel 框架,但我会将查询转换为框架。
您可以使用 NOT EXISTS 条件:
select c.*
from cars c
where not exists (select *
from electric_cars ec
where ec.non_valid_cars::jsonb @> to_jsonb(c.id)
and ec.cars_id = c.id);
请注意,建议在json
上使用jsonb
,因此您可能需要更改它以避免强制转换。
您可以将 json 数组转换为整数,然后只需执行not in
:
with excl as
(
select ec.id
, e::text::int nvid
from electric_cars ec, json_array_elements(non_valid_cars) e
where ec.id = 1
)
select *
from cars c
where c.id not in (select * from excl)
没有 CTE:
select *
from cars c
where c.id not in (select *
from (select e::text::int nvid
from electric_cars ec, json_array_elements(non_valid_cars) e
where ec.id = 1
) a
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.