Wednesday, 11 September 2013

MySQL Selecting a complex sub query as a field

MySQL Selecting a complex sub query as a field

I currently have:
SELECT tbl_review.*, users.first_name, users.last_name, (
SELECT order_ns.tran_date
FROM order_ns
LEFT JOIN product_2_order_ns.external_order_id = order_ns.order_id
WHERE product_2_order_ns.bkfno IN :id
ORDER BY order_ns.trandate ASC
LIMIT 1
) as purchase_date
FROM tbl_review
LEFT JOIN users ON users.sequal_user_id = tbl_review.user_id
WHERE tbl_review.product_id IN :id AND tbl_review.approved = 1
Which, in its sub query, selects an order the user has which has a product
in question (defined in :id) get the the oldest transaction date on file
for one of the found orders.
I would really like to keep this to one call of the database (don't really
want to call again for each returned user for just one field, or even do a
range query of all users) but obviously this particular query isn't
working.
What can I do, if anything, to get this working?
I cannot make the sub query into a join since they are two distinct pieces
of data, the sub query needs to return detail for each row in the main
query.

No comments:

Post a Comment