Consider a database with three tables:
goods (Id is the primary key)
+----+-------+-----+
| Id | Name  | SKU |
+----+-------+-----+
|  1 | Nails | 123 |
|  2 | Nuts  | 456 |
|  3 | Bolts | 789 |
+----+-------+-----+
invoiceheader (Id is the primary key)
+----+--------------+-----------+---------+
| Id |     Date     | Warehouse | BuyerId |
+----+--------------+-----------+---------+
|  1 | '2021-10-15' |         1 |     223 |
|  2 | '2021-09-18' |         1 |     356 |
|  3 | '2021-07-13' |         2 |       1 |
+----+--------------+-----------+---------+
invoiceitems (Id is the primary key)
+----+----------+--------+-----+-------+
| Id | HeaderId | GoodId | Qty | Price |
+----+----------+--------+-----+-------+
|  1 |        1 |      1 |  15 |   1.1 |
|  2 |        1 |      3 |   7 |   1.5 |
|  3 |        2 |      1 |  12 |   1.5 |
|  4 |        3 |      3 |   3 |   1.3 |
+----+----------+--------+-----+-------+
What I'm trying to do is to get the MAX(invoiceheader.Date) for every invoiceitems.GoodId. Or, in everyday terms, to find out, preferably in a single query, when was the last time any of the goods were sold, from a specific warehouse.
To do that, I'm using a derived query, and the solution proposed here . In order to be able to do that, I think that I need to have a way of giving multiple (well, two) aliases for a derived table.
My query looks like this at the moment:
SELECT tmp.*   /* placing the second alias here, before or after tmp.* doesn't work */
FROM (         /* placing the second alias, tmpClone, here also doesn't work */
    SELECT
        invoiceheader.Id,
        invoiceheader.Date,
        invoiceitems.HeaderId,
        invoiceitems.Id,
        invoiceitems.GoodId
    FROM invoiceheader
    LEFT JOIN invoiceitems
        ON invoiceheader.Id = invoiceitems.HeaderId
    WHERE invoiceheader.Warehouse = 3
    AND invoiceheader.Date > '0000-00-00 00:00:00'
    AND invoiceheader.Date IS NOT NULL
    AND invoiceheader.Date > ''
    AND invoiceitems.GoodId > 0
    ORDER BY 
        invoiceitems.GoodId ASC,
        invoiceheader.Date DESC
) tmp, tmpClone /* this doesn't work with or without a comma */
INNER JOIN (
    SELECT
        invoiceheader.Id,
        MAX(invoiceheader.Date) AS maxDate
    FROM tmpClone
    WHERE invoiceheader.Warehouse = 3
    GROUP BY invoiceitems.GoodId
) headerGroup
    ON tmp.Id = headerGroup.Id
    AND tmp.Date = headerGroup.maxDate
    AND tmp.HeaderId = headerGroup.Id
Is it possible to set multiple aliases for a single derived table? If it is, how should I do it?
I'm using 5.5.52-MariaDB.
 
     
    