mysqlinner-joinpsi

SQL error using INNER JOIN function to insert values


I'm having a problem with my simple SQL code as I'm just a beginner. I'm trying to retrieve the average value of outbound-cost-pal for different countries and write this in every corresponding line of Warehouse.

My code is the following:

INSERT INTO Warehouse (`inbound-cost-pal`)
SELECT cost.`average`
FROM Warehouse AS wh
INNER JOIN (
    SELECT  
    AVG     (`warehouse-cost-table`.`outbound-cost-pal`) AS `average`
    FROM    `warehouse-cost-table` 
            )cost
ON wh.`location-tariff-code` = LEFT(cost.`country`,2)
;

I'm receiving the error message 'Unknown column 'cost.country' in 'on clause''.


Solution

  • You forgot country in the select of subquery cost

    INSERT INTO Warehouse (inbound-cost-pal)
    SELECT cost.average
    FROM Warehouse AS wh
    INNER JOIN (
        SELECT  
        AVG     (warehouse-cost-table.outbound-cost-pal) AS average,
                country
        FROM    warehouse-cost-table 
                )cost
    ON wh.location-tariff-code = LEFT(cost.country,2)
    ;