SQL select where 条件 2 如果条件 1 不匹配
SQL select where conditions 2 if condition 1 doesn't match
我有点尴尬,觉得很惭愧,听起来很简单。但我对这个感到头脑发热
如果第一个条件不匹配任何条件,我想获得条件的结果。当然,我可以在我的 php 中使用一个简单的 if(!$request)
,但我想知道是否可以直接通过我的 sql 请求。
我已经做了一个简单的 OR 但当然这只会 return 每个条件的两个结果。
SELECT * FROM `menu` WHERE (`id_shop` = $current_shop OR `id_shop` = 0) AND `id_lang` = 1
如果没有对应于 $current_shop
id 的条目,我想获取那些 id_shop
等于 0 的条目。
If there is no entries coresponding to the $current_shop id, I want to get those where id_shop is equal to 0 instead.
您可以使用 UNION ALL
和 NOT EXISTS
来做到这一点:
SELECT *
FROM `menu`
WHERE `id_shop` = ? AND `id_lang` = 1
UNION ALL
SELECT *
FROM `menu`
WHERE `id_lang` = 1
AND `id_shop` = 0
AND NOT EXISTS (SELECT 1 FROM `menu` WHERE `id_shop` = ? AND `id_lang` = 1)
查询的第一个成员搜索具有给定参数的匹配项。当且仅当第一个成员没有 return 任何行时,第二个参数返回到 id_shop
0
。
SELECT * FROM 'menu' WHERE ('id_shop' = $current_shop OR ('id_shop' = 0 AND 'id_shop'
!= $current_shop)) AND 'id_lang' = 1
我有点尴尬,觉得很惭愧,听起来很简单。但我对这个感到头脑发热
如果第一个条件不匹配任何条件,我想获得条件的结果。当然,我可以在我的 php 中使用一个简单的 if(!$request)
,但我想知道是否可以直接通过我的 sql 请求。
我已经做了一个简单的 OR 但当然这只会 return 每个条件的两个结果。
SELECT * FROM `menu` WHERE (`id_shop` = $current_shop OR `id_shop` = 0) AND `id_lang` = 1
如果没有对应于 $current_shop
id 的条目,我想获取那些 id_shop
等于 0 的条目。
If there is no entries coresponding to the $current_shop id, I want to get those where id_shop is equal to 0 instead.
您可以使用 UNION ALL
和 NOT EXISTS
来做到这一点:
SELECT *
FROM `menu`
WHERE `id_shop` = ? AND `id_lang` = 1
UNION ALL
SELECT *
FROM `menu`
WHERE `id_lang` = 1
AND `id_shop` = 0
AND NOT EXISTS (SELECT 1 FROM `menu` WHERE `id_shop` = ? AND `id_lang` = 1)
查询的第一个成员搜索具有给定参数的匹配项。当且仅当第一个成员没有 return 任何行时,第二个参数返回到 id_shop
0
。
SELECT * FROM 'menu' WHERE ('id_shop' = $current_shop OR ('id_shop' = 0 AND 'id_shop'
!= $current_shop)) AND 'id_lang' = 1