我想在给定字段中选择具有最小值的子查询的所有行。以下是我迄今为止所尝试过的技术的一些玩具示例:
-- 1.
select
id, min(foo)
from
(select 1 AS id, 2 AS foo
union select 2 AS id, 2 AS foo
union select 3 AS id, 3 AS foo) a;
-- 2.
select
min(foo)
from
(
select 1 AS id, 2 AS foo, 0 AS const
union select 2 AS id, 2 AS foo, 0 AS const
union select 3 AS id, 3 AS foo, 0 AS const) a
group by const;
-- 3.
select
id
from
(select 1 AS id, 2 AS foo
union select 2 AS id, 2 AS foo
union select 3 AS id, 3 AS foo) a
where id = (select id from a where min(foo) = foo);
-- 4.
select
id
from
(select 1 AS id, 2 AS foo
union select 2 AS id, 2 AS foo
union select 3 AS id, 3 AS foo) a
where foo = (select min(foo));
-- 5.
select r.*
from
(
select min(foo) t
from
(select 1 AS id, 2 AS foo
union select 2 AS id, 2 AS foo
union select 3 AS id, 3 AS foo) a
) m
INNER JOIN a ON m.t = r.foo;
我正在处理的实际查询与示例类似,因为它由UNIONed组成的几个较小的查询组成。这里的总体目标是在中心表中根据与其连接的关联表 k 的字段查找行,其中 k 是最高优先级表。结果是一种来自相似(但不同的表)的行的树视图。
我已经提到了这一点,以防万一有人看到我以迂回的方式解决这个问题,他们可以对大局有所了解。但是现在我的角度是通过在子查询中的字段上取最小值来选择。
答案 0 :(得分:0)
使用order by
和limit
:
select t.*
from t
order by foo
limit 1;
注意:即使存在重复项,这也仅返回最小的一行。 t
是您的子查询或表格。
如果你想要所有这些,那么你需要包括两次表定义:
select t.*
from t
where t.foo = (select min(t2.foo) from t t2);