Stuck in building MySQL query

痴心易碎 提交于 2019-12-04 07:06:30

问题


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.


回答1:


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 



回答2:


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);



回答3:


Use this query:

SELECT id, item_id, user_id, min(bid_price) as bid_price 
FROM YOUR_TABLE_NAME 
GROUP BY item_id;


来源:https://stackoverflow.com/questions/49490275/stuck-in-building-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!