SQL将所有行排序为不重复

时间:2011-04-26 12:51:45

标签: mysql sql

我有一张看起来像这样的表:

________________________
|id|value|date|approved|
-----------------------

我需要做的是获得批准的每一行= 1.这部分是显而易见的。对于每次出现的值,我只想要最近的行(按日期排序)。

用这样的表来表示:

________________________
|id|value|date|approved|
-----------------------
|1 |Foo  | 5  |   1    |
|2 |Bar  | 6  |   1    |
|3 |Foo  | 8  |   1    |
-----------------------

我只想要id为2和3的行。

我认为我需要以某种方式使用DISTINCT,但我不确定如何。有人可以帮帮我吗?

6 个答案:

答案 0 :(得分:4)

SELECT  m.*
FROM    (
        SELECT  DISTINCT value
        FROM    mytable
        ) md
JOIN    mytable m
ON      m.id =
        (
        SELECT  id
        FROM    mytable mi
        WHERE   mi.value = md.value
                AND mi.approved = 1
        ORDER BY
                mi.value DESC, mi.date DESC, mi.id DESC
        LIMIT 1
        )

(value, date, id)上创建一个索引,以便快速工作。

答案 1 :(得分:1)

你需要:

select id, value, date, approved where (value, date) in (
   select value, max(date)
     from your_table
    group by value
);

答案 2 :(得分:0)

实际上使用GROUP BY会产生更好的效果。尝试这样的事情:

SELECT idvaluedateapproved FROM表WHERE approved = 1 GROUP BY value ORDER BY date;

答案 3 :(得分:0)

select  id, value, date, approved 
from mytable a
where approved = 1
 and date =
      (select max(b.date)
       from mytable b
       where b.approved = 1
       and b.value = a.value)

答案 4 :(得分:0)

select 
      id,
      value,
      date
   from 
      ( select
              value, max( date ) as LastInstance
           from
              YourTable
           where
              approved = 1
           group by
              value ) PreQuery
      join YourTable 
         on PreQuery.value = YourTable.value
         and PreQuery.LastInstance = YourTable.LastInstance
         and YourTable.approved = 1
   order by 
      date

答案 5 :(得分:-2)

试试这个:

SELECT * DISTINCT FROM TABLA WHERE APPROVED = 1 ORDER BY DATE DESC

希望这会对你有所帮助。