选择id最高且具有公共字段的列

时间:2014-02-21 16:36:26

标签: mysql sql select join

我有一张名为iview的表:

gpreq_id    a_id   m_id     rcv_qty
1           100      4         0
2           100      4         1
3           100      5         4
4           101      4         1
5           101      4         10
6           101      4         1

如何选择a_id中的m_id具有最高gpreq_id?

像:

gpreq_id    a_id   m_id     rcv_qty
2           100      4         1
3           100      5         4
6           101      4         1

2 个答案:

答案 0 :(得分:1)

尝试类似

的内容
SELECT i1.*
FROM iview as i1
WHERE i1.gpreq_id IN (SELECT MAX(gpreq_id) 
                     FROM iview as i2 
                     GROUP BY i2.a_id, i2.m_id)

以下是 SQL FIDDLE

答案 1 :(得分:1)

首先找到每个a_id, m_id对的最大值,然后加入iview:

select i.* 
 from iview as i 
  inner join (
  select a_id, m_id, max(gpreq_id) as max_gpreq_id
   from iview 
  group by a_id, m_id
) as mi on (mi.max_gpreq_id = i.pgreq_ie)