我正在尝试返回foo的所有值,这些值的最大值为bar,其中foo.val> bar.val
CREATE TABLE `foo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`val` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `bar` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`val` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
insert into foo (val) values (3), (5), (7), (10);
insert into bar (val) values (1), (1), (2), (3), (4), (5), (6), (7), (8), (20);
预期输出如下:
+--------+---------+------------------------+
| foo.id | foo.val | max(bar.val) < foo.val |
+--------+---------+------------------------+
| 1 | 3 | 2 |
| 2 | 5 | 4 |
| 3 | 7 | 6 |
| 4 | 10 | 8 |
+--------+---------+------------------------+
这可以通过单个查询完成,而不是在代码域中循环吗?
SELECT max(val) from bar where val < 3;
SELECT max(val) from bar where val < 5;
SELECT max(val) from bar where val < 7;
SELECT max(val) from bar where val < 10;
有人对此有任何想法吗?
如果有人想尝试http://sqlfiddle.com/#!2/de0f9/7
,小提琴就在这里提前致谢。
答案 0 :(得分:3)
select foo.id
, foo.val
, max(bar.val)
from foo
left join
bar
on bar.val < foo.val
group by
foo.id
, foo.val
Example at SQL Fiddle(感谢JohnWhoo)
答案 1 :(得分:2)
select foo.id,
foo.val,
(select MAX(bar.val) from bar where bar.val < foo.val) as barval
from foo
它将返回null,在bar中找不到更小的值,如果需要值,可以使用coalesce。
答案 2 :(得分:0)
SELECT f.id, f.val, (SELECT MAX(b.val) FROM bar b WHERE b.val<f.val) FROM foo f;