我有兩張桌子:
汽車表,其中包含:
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]
如何從汽車表中選擇所有記錄,這些記錄不在electric_cars 列中id 的non_valid_cars 陣列中,id 為cars_id?
另外,我正在使用 Laravel 框架,但我會將查詢翻譯到框架中。
非常感謝你的幫助。
uj5u.com熱心網友回復:
您可以使用 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因此您可能需要更改它以避免強制轉換。
uj5u.com熱心網友回復:
您可以將 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
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/415491.html
標籤:
