I’m trying to return all values of foo joined with the max values of bar where 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);
The expected output would be like:
+--------+---------+------------------------+
| foo.id | foo.val | max(bar.val) < foo.val |
+--------+---------+------------------------+
| 1 | 3 | 2 |
| 2 | 5 | 4 |
| 3 | 7 | 6 |
| 4 | 10 | 8 |
+--------+---------+------------------------+
Can this be done with a single query rather than looping through in code-land?
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;
Anyone have any ideas on this?
Fiddle is here if anyone wants to try it http://sqlfiddle.com/#!2/de0f9/7
Thanks in advance.
It will return null in no smaller value is find in bar, maybe use coalesce if you need a value.