I have three tables, e.g. fruits
:
+----+--------+---------+
| id | type | variety |
+----+--------+---------+
| 1 | orange | 5 |
| 2 | orange | 7 |
| 3 | apple | 1 |
| 4 | apple | 0 |
+----+--------+---------+
containers
:
+----+--------+
| id | year |
+----+--------+
| 1 | 2015 |
| 2 | 2020 |
| 3 | 2020 |
| 4 | 2018 |
+----+--------+
and inclusion
:
+----+----------+---------+
| id | fruit_id | cont_id |
+----+----------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 3 | 2 |
| 5 | 3 | 3 |
| 6 | 3 | 4 |
+----+----------+---------+
I need to select "newest" container for each fruit variety if there is any:
+----+--------+----------+------+
| id | type | variety | year |
+----+--------+----------+------+
| 1 | orange | 5 | 2020 |
| 2 | orange | 7 | 2015 |
| 3 | apple | 1 | 2020 |
| 4 | apple | 0 | NULL |
+----+--------+----------+------+
I'm trying something like
SELECT * FROM `fruits`
LEFT JOIN (SELECT * FROM `containers`
JOIN `inclusion` ON `inclusion`.`cont_id` = `containers`.`id`
WHERE `fruit_id` = `fruits`.`id`
ORDER BY `year` DESC LIMIT 1
) `tops` ON `tops`.`fruit_id` = `fruits`.`id`;
but it says
ERROR 1054 (42S22): Unknown column 'fruits.id' in 'where clause'
is there any way to get the required result?
I'm using mariadb
my now, but migration to mysql
could happen, so I need a solution working on both servers.
What if I also add cnt_type
table:
+----+---------+
| id | type |
+----+---------+
| 1 | box |
| 2 | package |
+----+---------+
and containers
would include type:
+----+--------+------+
| id | year | type |
+----+--------+------+
| 1 | 2015 | 1 |
| 2 | 2020 | 1 |
| 3 | 2020 | 2 |
| 4 | 2018 | 2 |
+----+--------+------+
so I need to extract top-year of each container type including each fruit variety?
+----+--------+----------+----------+------+
| id | type | variety | cnt_type | year |
+----+--------+----------+----------+------+
| 1 | orange | 5 | box | 2020 |
| 1 | orange | 5 | package | NULL |
| 2 | orange | 7 | box | 2015 |
| 2 | orange | 7 | package | NULL |
| 3 | apple | 1 | box | 2020 |
| 3 | apple | 1 | package | 2020 |
| 4 | apple | 0 | box | NULL |
| 4 | apple | 0 | package | NULL |
+----+--------+----------+----------+------+
In this case combination type
-year
for each container should be unique.