我有一个示例表“ city”,如下所示:
inputHidden
如果我提供的城市不存在,我可以写一个返回id | city
----------------
1 London
2 Liverpool
3 Birmingham
4 (Other)
的查询吗...
(Other)
我知道第二个SELECT语句将不返回任何内容。但是,如何修改它以返回“(其他)”行?概念代码:
SELECT * FROM cities WHERE city = "London" --> {1, London}
SELECT * FROM cities WHERE city = "Manchester" --> {4, (Other) }
答案 0 :(得分:4)
一种方法是:
select c.*
from cities c
where c.city in (?, '(Other)')
order by c.city = '(Other)'
limit 1;
这将检索可能匹配的两行(?
是所需名称的占位符)。如果有两行,则选择一个不是“其他”的行。
答案 1 :(得分:2)
考虑:
select *
from cities
where
city = 'Manchester'
or (city = '(Other)' and not exists (select 1 from cities where city = 'Manchester'))
答案 2 :(得分:0)
select DISTINCT 'Other' AS city
FROM cities WHERE NOT EXISTS (select * from cities where city = 'Brisbane')
UNION ALL
SELECT city from cities where city = 'Brisbane'
答案 3 :(得分:0)
使用self join
并稍加扭曲
select a.id, a.city
from (select *, city = '(Other)' as other from cities) a
left join cities b on b.city = 'London'
where a.city = b.city or (b.city is null and a.other = 1)