Search code examples
mysqlsubqueryin-subquery

How select unique minimum value from more tables


I have following problem.

In MySQL I have two tables:

Table A
---------------------------
| idOffer| price
| 4      | 20
| 4      | 30
| 5      | 15
| 5      | 18
| 6      | 6
| 4      | 9
--------------------------------------------------

Table B
---------------------------
| idOffer| price
| 4      | 60
| 4      | 70
| 5      | 10
| 5      | 8
| 6      | 90
| 6      | 100
--------------------------------------------------

Is there possible query, which return result like

| idOffer| price
| 4      | 20
| 5      | 8
| 6      | 6

Solution

  • Here's one option with a union all statement:

    select idoffer, min(price)
    from (
        select idoffer, price from tablea
        union all
        select idoffer, price from tableb
    ) t
    group by idoffer