MySQL:选择只存在一个唯一Max记录的位置

时间:2017-02-03 07:24:22

标签: mysql codeigniter

我的数据是:

bid_id,  fkp_id, fkb_id, bid_amount
1  ,        13 ,   1 ,  22000  
2 ,         13 ,   2 ,  23000  
3 ,         13 ,   2 ,  23000 
4,          3  ,   1 ,  5000
5,          3  ,   2 ,  6000 

如果存在平局(在本例中为bid_id 2和bid_id 3),则不应选择此记录,并且只应选择唯一的最大bid_amount值记录。

在这种情况下,所需记录为bid_id 1和bid_id 5

1 个答案:

答案 0 :(得分:1)

如果您需要一个唯一的最大金额,请查看您的数据 并且最大金额与您可以使用的金额本身相关

  select bid_id, fkp_id, fkb_id, bid_amount
  from table_name 
  where bid_amount = (  select max(t.bid_amount)
          from ( select bid_amount, count(*)
                from table_name
                group by bid_amount
                having count(*) = 1 ) t )

如果您的唯一最大金额是针对flp_id,那么您也可以正确地为此列提供分组

select bid_id, fkp_id, fkb_id, bid_amount
from table_name 
where ( fkp_id, bid_amount)  in  (  select  t.fkp_id, max(t.bid_amount)
        from ( select fkp_id, bid_amount, count(*)
              from table_name
              group by fkp_id, bid_amount
              having count(*) = 1 ) t 
         group by t.fkp_id )