sql 查询从两个具有不同优先级的查询返回结果
sql query returning result from two queries with different priorities
我想在单个查询中实现的是 return 符合特定条件的记录的 ID,如果没有找到,则使用另一个条件。所以这两个标准有不同的优先级,简单的 'or' 是行不通的。
我想出了两个解决方案,但想知道是否可以简化:
select id,1 as n from <tablename> where <criterion1>
union select id,2 as n from <tablename> where <criterion2>
order by n asc limit 1;
或:
select coalesce ((select id from <tablename> where <criterion1>),
(select id from <tablename> where <criterion2>));
我更喜欢的是不必重复两个查询的共同点(实际上我 select 更多列,因此必须并行维护这些),并且两个查询关注相同table.
如果有捷径,我很乐意了解它。
如果您想要一行,请使用 order by
和 limit
:
select t.*
from t
where <criterion1> or <criterion2>
order by (case when <criterion1> then 1 else 2 end)
limit 1;
我想在单个查询中实现的是 return 符合特定条件的记录的 ID,如果没有找到,则使用另一个条件。所以这两个标准有不同的优先级,简单的 'or' 是行不通的。
我想出了两个解决方案,但想知道是否可以简化:
select id,1 as n from <tablename> where <criterion1>
union select id,2 as n from <tablename> where <criterion2>
order by n asc limit 1;
或:
select coalesce ((select id from <tablename> where <criterion1>),
(select id from <tablename> where <criterion2>));
我更喜欢的是不必重复两个查询的共同点(实际上我 select 更多列,因此必须并行维护这些),并且两个查询关注相同table.
如果有捷径,我很乐意了解它。
如果您想要一行,请使用 order by
和 limit
:
select t.*
from t
where <criterion1> or <criterion2>
order by (case when <criterion1> then 1 else 2 end)
limit 1;