Stuck in building MySQL query

后端 未结 3 381
后悔当初
后悔当初 2021-01-29 12:54

Given an example of table:

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

The task is to select rows wi

相关标签:
3条回答
  • 2021-01-29 12:59

    Use this query:

    SELECT id, item_id, user_id, min(bid_price) as bid_price 
    FROM YOUR_TABLE_NAME 
    GROUP BY item_id;
    
    0 讨论(0)
  • 2021-01-29 13:01

    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 
    
    0 讨论(0)
  • 2021-01-29 13:03

    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);
    
    0 讨论(0)
提交回复
热议问题