Stuck in building MySQL query

2019-03-07 10:13发布

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.

3条回答
小情绪 Triste *
2楼-- · 2019-03-07 10:17

Use this query:

SELECT id, item_id, user_id, min(bid_price) as bid_price 
FROM YOUR_TABLE_NAME 
GROUP BY item_id;
查看更多
别忘想泡老子
3楼-- · 2019-03-07 10:24

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 
查看更多
虎瘦雄心在
4楼-- · 2019-03-07 10:33

You can use MIN() with GROUP BY in the query:

SELECT id, item_id, MIN(bid_price) AS min_bid, user_id 
FROM your_tbl 
GROUP BY item_id 
HAVING item_id in(1, 2, 3);
查看更多
登录 后发表回答