我必須根據兩個欄位查詢表,如果第一個欄位匹配,則不檢查第二個欄位,但如果第一個欄位不匹配,則檢查第二個欄位是否匹配一個值
就像是:
SELECT * FROM table
WHERE cart_id=389 OR (cart_id IS NULL AND user_id=26)
但是如果第一個條件成功,它不能檢查第二個條件
例子:
假設以下是我的表
id | cart_id | user_id
1 | 389 | 26
2 | null | 26
3 | 878 | 26
- 在查詢 cart_id = 389 和 user_id = 26 時,我應該只取回記錄 1 而不是 2
- 在查詢 cart_id = 1 和 user_id = 26 時,我應該只取回記錄 2 而不是 1 和 3
uj5u.com熱心網友回復:
我能想到的唯一方法是分兩步執行此操作,并在第二步中檢查第一步的結果:
with the_cart as (
SELECT *
FROM the_table
WHERE cart_id=389
)
select *
from the_cart
union all
select *
from the_table
where cart_id IS NULL
AND user_id=26
and not exists (select * from the_cart);
如果第一個查詢(使用cart_id=389)回傳某些內容,則聯合中的第二個查詢將由于條件而不會運行(或更準確地說,不回傳任何行)not exists()。
在線示例
uj5u.com熱心網友回復:
根據您更新的示例資料,您的 where 子句將是:
WHERE cart_id = 389 and user_id = 26
但考慮到這是多么微不足道,很難相信這真的是你一直在問的問題。
=== 根據最新示例更新...
WHERE (cart_id = 389 and user_id = 26)
OR (cart_id is null and user_id = 26)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446059.html
標籤:sql PostgreSQL
