我必须基于两个字段查询一个表,这样,如果第一个字段匹配,则不检查第二个字段,但如果第一个域不匹配,则检查第二字段是否匹配值
类似于:
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和NOT 2
- 在查询cart_id=1和user_id=26时,我应该只返回记录2,而不是1和3
我能想到的唯一方法是分两步完成,并在第二步中检查第一步的结果:
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()
条件,联合中的第二个查询将不会运行(或者更准确地说,不返回任何行(。
在线示例
根据更新的示例数据,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)