Note that there are some explanatory texts on larger screens.

plurals
  1. POSubquery and selecting oldest rows for multiple foreign keys in MySQL
    primarykey
    data
    text
    <p>I have two tables:</p> <pre><code>product (idproduct, name, description, tax) product_storage (idstorage, idproduct, added, quantity, price) </code></pre> <p>for each product it could be different price and oldest are "first-to-sell"</p> <p>for example in storage I have:</p> <pre><code>1, 1, 2010-01-01, 0, 10.0 2, 1, 2010-01-02, 0, 11.0 3, 1, 2010-01-03, 10, 12.0 4, 2, 2010-01-04, 0, 12.0 5, 2, 2010-01-05, 10, 11.0 6, 2, 2010-01-06, 10, 13.0 7, 3, 2010-01-07, 10, 14.0 8, 3, 2010-01-08, 10, 16.0 9, 3, 2010-01-09, 10, 13.0 </code></pre> <p>and now I need to select all products with current price, which is in the oldest row in product_storage where quantity > 0 for each product:</p> <pre><code>SELECT p.idproduct, p.name, p.tax, (SELECT s.price FROM product_storage s WHERE s.idproduct=p.idproduct AND s.quantity &gt; 0 ORDER BY s.added ASC LIMIT 1) AS price FROM product p; </code></pre> <p>works fine, but it doesn't when I want to calculate price with tax in query:</p> <pre><code>SELECT p.idproduct, p.name, p.tax, (SELECT s.price FROM product_storage s WHERE s.idproduct=p.idproduct AND s.quantity &gt; 0 ORDER BY s.added ASC LIMIT 1) AS price, (price * (1 + tax/100)) AS price_with_tax FROM product p; </code></pre> <p>MySQL says:</p> <pre><code>Unknown column 'price' in 'field list' </code></pre> <p><strong>Update</strong></p> <p>Using subquery as a table almost solves problem (look at answers) - the only question now is how to select oldest rows from product_storage for multiple foreign keys (one and only one for each idproduct).</p> <p><strong>Update 2</strong></p> <p>Thanks to cmptrgeekken for great solution :))</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload