我需要按一列查找记录,但如果没有记录,我需要在另一列中搜索,但第一列优先。
考虑情景:
find records matching column_1
if no records matching column_1, find records matching column_2
if records matching column_1 found, find the subset which also match column_2
如何构建此类查询?
答案 0 :(得分:1)
你不关心where
条款各部分的顺序 - 它们可以随意互换,这是一件好事。
使用or
运算符的常用方法就是使用where column_1 = @param or column_2 = @param
运算符:
select
case when column_1 = @param then 'Matched first!'
else 'Matched second!' end as Status
查询不允许您将同一行返回两次或更多次,它只将过滤器应用于每行一次(逻辑上)。
三种情景之间应该有什么区别?如果要返回一些额外状态,可以使用select子句,例如:
union all
如果你想这样做,你必须复制你的查询三次,并使用select ... from ...
where column_1 = @param
union all
select ... from ...
where column_1 <> @param and column_2 = @param
加入三个查询的结果,例如。像这样的东西:
{{1}}
等
答案 1 :(得分:1)
希望这会有所帮助
从tablex中选择,(从tablex中选择count(*)n,其中column1 =“condition”)n where
(n.n&lt;&gt; 0和column2 =“condition”和column1 =“condition”)或(n.n = 0和column2 =“condition”)
答案 2 :(得分:1)
此类查询(尝试查找具有特定条件的记录,如果失败则尝试使用其他标准)很复杂。
这是您的标准:
更密切地看待这一点,归结为:
或:
以下是声明:
select * from mytable
where column_2 = 'match2'
and
(
column_1 = 'match1'
or
(select count(*) from mytable where column_1 = 'match1') = 0
);