MySQL:当WHERE找到类似条目时,选择最高列值

时间:2012-11-27 11:02:35

标签: mysql sql select max where

我的问题与this one相当,但不完全相同。

我有一个包含大量书籍的数据库,其中包含一些相同书籍的不同版本。我正在寻找一个SQL语句,为我提供了我用WHERE子句选择的每个标题的最高版本号(查找特定的书籍系列)。这是表格的样子:

|id|title                    |edition|year|
|--|-------------------------|-------|----|
|01|Serie One Title One      |1      |2007|
|02|Serie One Title One      |2      |2008|
|03|Serie One Title One      |3      |2009|
|04|Serie One Title Two      |1      |2001|
|05|Serie One Title Three    |1      |2008|
|06|Serie One Title Three    |2      |2009|
|07|Serie One Title Three    |3      |2010|
|08|Serie One Title Three    |4      |2011|
|--|-------------------------|-------|----|

我正在寻找的结果是:

|id|title                    |edition|year|
|--|-------------------------|-------|----|
|03|Serie One Title One      |3      |2009|
|04|Serie One Title Two      |1      |2001|
|08|Serie One Title Three    |4      |2011|
|--|-------------------------|-------|----|

我最接近的是使用这句话:

select id, title, max(edition), max(year) from books where title like "serie one%" group by title;

但它会返回最高版本和年份,并包含它找到的第一个ID:

|--|-----------------------|-------|----|
|01|Serie One Title One    |3      |2009|
|04|Serie One Title Two    |1      |2001|
|05|Serie One Title Three  |4      |2011|
|--|-----------------------|-------|----|

这种花哨的联系也很接近,但没有给出正确的结果:

select b.id, b.title, b.edition, b.year from books b inner join (select name, max(edition) as maxedition from books group by title) g on b.edition = g.maxedition where b.title like "serie one%" group by title;

使用这个我获得了独特的标题,但大部分都是旧版本。

3 个答案:

答案 0 :(得分:2)

您可以使用子查询:

select b1.id, 
  b1.title,
  b1.edition,
  b1.year
from books b1
inner join
(
  select max(edition) edition, title
  from books
  group by title
) b2
  on b1.edition = b2.edition
  and b1.title = b2.title

请参阅SQL Fiddle with Demo

或者您可以使用IN子句:

select id, title, edition, year
from books b
where edition in (select max(edition)
                  from books b1
                  where b.title = b1.title
                  group by title);

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

这是SQLFiddle example

在MySql中你可以这样做:

select id,title,edition,year from
(
      select id,title,edition,year,
      @i:=if(@title=title,@i+1,1) rn,
      @title:=title 
      from t, (select @i:=0,@title:='') d 
      order by title,edition Desc,year desc
) d where rn=1

答案 2 :(得分:0)

最简单的方法:

select * from (select id, title, edition, year from books order by title, edition desc) group by title;