从一个表中获取所有ID不在另一个表JSON数组列中的所有项目?

3

我有两个表:

汽车表,其中包含:

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]

如何从cars表中选取所有不在electric_cars列的non_valid_cars id数组中的记录?
此外,我正在使用Laravel框架,但我将把一个查询转换为该框架。
1个回答

2
您可以使用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);

请注意,建议使用 jsonb 而不是 json,因此您可能希望更改以避免转换。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接