Ollivander's Inventory

  • + 0 comments

    MySQL Query:

        (select w.id 
         from
            wands w
            inner join
            wands_property wt
            on w.code = wt.code
         where w.power = wa.power 
            and wt.age = wp.age 
            and w.coins_needed = min(wa.coins_needed)
         limit 1
        ) wand_id,
        wp.age wand_age,
        min(wa.coins_needed) wand_price,
        wa.power wand_power
    from
        wands wa
        inner join
        wands_property wp
        on wa.code = wp.code
    where wp.is_evil = 0
    group by wa.power, wp.age
    order by wa.power desc, wp.age desc;
    

    Exaplanation:

    This query worked in MySQL because MySQL is lenient and allows the use of aggregate functions like MIN() inside the WHERE clause of a subquery, even though this is not strictly valid in standard SQL. In proper ANSI SQL, aggregate functions can only appear in the SELECT or HAVING clauses or within subqueries that include a GROUP BY. MySQL implicitly treats the MIN() as an aggregation over the entire subquery, which is why it doesn't throw an error, but this behavior is not portable to stricter SQL databases like PostgreSQL, SQL Server, or Oracle, where such a query would fail. To ensure strict correctness and portability, the subquery should either use GROUP BY to compute the minimum or, more efficiently, apply window functions like ROW_NUMBER() to select the minimum value per group. So while your logic and result were correct for the immediate context, the technical application of MIN() in the WHERE clause is not universally valid SQL.