mariadbsubquery

MariaDb Use Column In primary Query in sub Query


I have a table that has store names, product codes and prices. I need to pull the minimum price of a product and display a list of the product codes with their minimum price, where it all falls down is i need to display the store name that has the minimum price. to do this i need to use the minimum price and product code i get in the primary query and pass it to a sub query to get the store name but do not know how to do this.

SELECT 
    `Code`, 
    `wholsalerName`.`wholesaler`,
    min(round(`Price`,2))  as 'minPriceCol'
FROM `Listings_Lines` as listingLines
left join (
    select 
        `Code`, 
        `wholesaler` 
    from `Listings_Lines` 
    WHERE Price = listingLines.`minPriceCol`) as wholsalerName 
    on wholsalerName.Code = `Listings_Lines`.`Code`
WHERE `Listings_Lines`.`wholesaler` <> 'Pharmacon' and `Price` > 0
group BY `code`

this gives me an unknow column error

#1054 - Unknown column 'listingLines.minPriceCol' in 'where clause'


Solution

  • SELECT 
        ll.Code, 
        ll.wholesaler,
        min_prices.minPriceCol
    FROM 
        `Listings_Lines` AS ll
    JOIN (
        SELECT 
            Code, 
            MIN(ROUND(Price, 2)) AS minPriceCol
        FROM 
            `Listings_Lines`
        WHERE 
            wholesaler <> 'Pharmacon' AND Price > 0
        GROUP BY 
            Code
    ) AS min_prices 
    ON ll.Code = min_prices.Code AND ROUND(ll.Price, 2) = min_prices.minPriceCol
    WHERE 
        ll.wholesaler <> 'Pharmacon' AND ll.Price > 0;