Here is the current query i am trying to convert, it takes ONE item id and then receives the corresponding price/qty/vendor_id with the most recent date and a type that is not equal to TRAN.
SELECT cs_po_products.price, cs_po_products.qty, cs_po.vendor_id
FROM cs_po_products, cs_po
WHERE cs_po_products.stock_number = :items_id
AND cs_po_products.po_number = cs_po.id
AND type !='TRAN'
ORDER BY cs_po.date_ordered DESC
LIMIT 1
This query works fine, however it has to be done quite a few time which makes loading the page a bit slow. I am trying to create a query that will get the ROW of the Newest date_ordered for EVERY stock_number. While searching for an answer i have come across quite a few techniques but the most common being a JOIN of the two tables with a MAX() of date_ordered in the join. But alas i cannot seem to come up with the correct query.
This is one of many attempts but the one i think is the closest.
SELECT a.price, a.qty, b.vendor_id, a.stock_number, b.max, b.type
FROM cs_po_products a
LEFT JOIN (SELECT MAX(date_ordered)as max,vendor_id,type, date_ordered,id FROM cs_po) b
ON b.id = a.po_number
WHERE stock_number != '' AND date_ordered IS NOT NULL
AND type !='TRAN'
ORDER BY stock_number, date_ordered DESC
If anyone could point me in the right direction, thanks in advance
EDIT:
all of the answers provided still give more than one row for a stock number, for example:
price qty vendor_id stock_number date_ordered
0.05446 123750 51 00010005.01S 2014-02-24 15:29:00
0.05446 123750 51 00010005.01S 2014-01-02 14:25:00
0.05446 123750 51 00010005.01S 2013-11-04 13:48:00
0.05402 123750 51 00010005.01S 2013-08-20 10:02:00
0.0532 123750 51 00010005.01S 2013-07-12 09:21:00
0.0538 123750 51 00010005.01S 2013-04-02 12:15:00
0.0532 123750 51 00010005.01S 2012-12-27 00:00:00
0.0555 101750 51 00010005.01S 2012-11-07 10:55:00
0.555 137500 51 00010005.01S 2012-11-02 09:39:00
0.0532 137500 51 00010005.01S 2012-11-02 09:37:00
0.0532 123750 51 00010005.01S 2012-10-03 00:00:00
the ONLY row i want in this result is the top one because it has the most recent date, but in the actual results there is many more stock_numbers below which i want those corresponding max dates aswell