限制mysql结果

时间:2012-03-07 12:47:59

标签: mysql

我正在尝试编写一个SQL语句来返回一个人的每个主题的最新记录,

Database
Counter,Name,Subject,Grade
1,PersonA,Maths,C
2,PersonB,Maths,B
3,PersonA,English,B
4,PersonB,English,A
5,PersonA,Maths,A
6,PersonB,Maths,B

我想返回PersonA的最新结果

5,PersonA,Maths,A
3,PersonA,English,B

如何实现这一目标?

4 个答案:

答案 0 :(得分:3)

Select t1.Name,t1.Subject,t1.Grade
From SomeTableName t1
inner join (Select Name,Subject,Max(Counter) As Counter 
            From SomeTable 
            Group By Name,Subject) t2
On t1.counter = t2.counter

答案 1 :(得分:1)

你可能需要这样做:

SELECT * FROM TABLE_NAME WHERE Name='PersonA' ORDER BY Counter DESC LIMIT 2;

答案 2 :(得分:0)

如果您只能在结果中使用分组列,那么这也有效:

SELECT *
  FROM database
 WHERE counter IN(SELECT max(counter)
                    FROM database
                   GROUP BY subject)
  AND name 'PersonA'

答案 3 :(得分:0)

试试这个:

select * from
(SELECT distinct columnA, columnB, MAX(counter) as id FROM table_name
group by columnA, columnB) as table1
inner join (select * from table_name) as table2 on table1.counter = table2.counter