Search code examples
phpmysqlsymfonydoctrinedql

Stuck in building MySQL query


Given an example of table:

id | item_id | user_id | bid_price
----------------------------------

The task is to select rows with minimum bid_price for each item_id in the provided set.

For example: item_id = [1, 2, 3] - so I need to select up to three (3) rows, having a minimum bid_price.

Example of data:

id | item_id | user_id | bid_price
----------------------------------
 1 |    1    |   11    |     1
 2 |    1    |   12    |     2
 3 |    1    |   13    |     3
 4 |    1    |   14    |     1
 5 |    1    |   15    |     4
 6 |    2    |   16    |     2
 7 |    2    |   17    |     1
 8 |    3    |   18    |     2
 9 |    3    |   19    |     3
10 |    3    |   18    |     2

Expected result:

id | item_id | user_id | bid_price
----------------------------------
 1 |    1    |   11    |     1
 7 |    2    |   17    |     1
 8 |    3    |   18    |     2

Actually, I'm using Symfony/Docine DQL, but it will be enough with a plain SQL example.


Solution

  • For the all the columns in the rows you could use a inner join on subselect for min bid price

    select m.id, m.item_id, m.user_id, m.bid_price
    from my_table m 
    inner join ( 
    select item_id, min(id) min_id,  min(bid_price) min_price
    from my_table 
    where   item_id IN (1,2,3)
    group by item_id 
    ) t on t.item_id = m.item_id 
       and t.min_price= m.bid_price
       and t.min_id = m.id
    

    or .. if you have some float data type you could use a acst for unsigned

      select m.id, m.item_id, m.user_id, cast(m.bid_price as UNSIGNED) 
      from my_table m 
      inner join ( 
      select item_id, min(id) min_id,  min(bid_price) min_price
      from my_table 
      where   item_id IN (1,2,3)
      group by item_id 
      ) t on t.item_id = m.item_id 
         and t.min_price= m.bid_price
         and t.min_id = m.id