我有一個 SQL 查詢,它將資料庫中的產品串列作為 JSON 物件回傳,如下所示:
select json_build_object('has_product', 'true', 'product_id', product_id)
from products
where id in (10, 65, 75);
這是結果:
{"has_product" : "true", "product_id" : 10}
{"has_product" : "true", "product_id" : 65}
但是對于product_id: 75我沒有結果,因為它不存在,我希望它回傳如下內容:
{"has_product" : "false", "product_id" : null}
我找到了一個解決方案,但我想知道是否有更快更干凈的方法來做到這一點:
select row_to_json(req)
from (
select
case (coalesce((select product_id from products where product_id = 10), 0))
when 0 then 'false'
when 10 then 'true'
end has_product,
case (coalesce((select product_id from products where product_id = 10), 0))
when 0 then 'null'
when 10 then '10'
end product_id
-- union all
-- same request for id 65
union all
select
case (coalesce((select product_id from products where product_id = 75), 0))
when 0 then 'false'
when 75 then 'true'
end has_product,
case (coalesce((select product_id from products where product_id = 75), 0))
when 0 then 'null'
when 75 then '75'
end product_id
) req
uj5u.com熱心網友回復:
不是使用 過濾in,而是即時構建一個包含所有所需產品 ID 的表,然后對其進行右連接。它將為您想要的每個產品 ID 創建一行。然后,您可以通過檢查product_id反對來判斷產品是否存在于您的主表中null。對于您在主表中沒有條目的產品 ID,它將是null,對于那些您擁有它的產品 ID,它將是非空的。
select
json_build_object('has_product', product_id is not null, 'product_id', desired_product_id)
from
products
right join
unnest(ARRAY[10, 65, 75]) desired_product_id
on product_id = desired_product_id;
uj5u.com熱心網友回復:
而不是使用IN(),使用LEFT JOIN...
WITH
list(id) AS
(
SELECT 10
UNION ALL SELECT 65
UNION ALL SELECT 75
)
SELECT
json_build_object(
'has_product', CASE WHEN products.id IS NULL THEN 'false' ELSE 'true' END,
'product_id', products.product_id
)
FROM
list
LEFT JOIN
products
ON products.id = list.id
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/321599.html
標籤:sql PostgreSQL
