3

I have two MySQL tables:

  • tbl_product: product_id, product_name, update_time, sale
  • tbl_child_product: child_id, child_name, child_price, product_id

How to select all product with sale='1', order by update_time, the lowest price per product (store in child_price in tbl_child_product table) with one query?

Thank you!

3 Answers 3

2

May be UNION clause will help you.

(SELECT * from tbl_product where product_id = 'NULL') UNION (SELECT * from tbl_child_product where child_id = 'NUll')

and so on for all values .

Sign up to request clarification or add additional context in comments.

Comments

2

You can use inner join of both the tables as:

Select p.product_id, p.product_name, min(c.child_price), p.update_time
from tbl_product p inner join tbl_child_product c
on p.product_id = c.product_id
group by p.product_id
having sale='1'
order by p.update_time

Updated the answer as per question: Use having sale='1' to filter the results of group by

Comments

1

You could join between tbl_product and an aggregate query on tbl_child_product:

SELECT   p.product_id, p.product_name, c.lowest_price
FROM     tbl_product p
JOIN     (SELECT   product_id, MIN(child_price) lowest_price
          FROM     tbl_child_product
          GROUP BY product_id) c ON p.product_id = c.product_id
ORDER BY p.update_time

3 Comments

Hello, i use your query but it show up one product only, insteads of showing all product (order by update_time) with lowest price per product. Please help!
@hatxi This query should work, but maybe I misunderstood the requirement. Please edit your question with some sample data and the result you're trying to achieve.
I updated the question: list all products that match the condition (sale=1) and include the min price of each product. The product list will order by update_time. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.