将列中的最后一个条目选为其他列中的唯一条目

时间:2015-09-24 21:05:49

标签: php mysql

尝试从下表中获取最后一条唯一记录。其中有一些双打,应该过滤掉。

id  topic   action  date
1   10127   2   2015-09-24 15:28:30
2   10127   4   2015-09-24 15:29:26
3   10127   2   2015-09-24 15:30:01
4   10127   3   2015-09-24 15:30:55
5   10127   1   2015-09-24 16:07:25
6   10127   5   2015-09-24 16:10:25
7   10127   4   2015-09-24 16:29:26

使用此查询(在此处找到)是我的最大努力,但只返回一个结果。

SELECT MAX(action) as action,topic,date FROM ...... 
GROUP by topic 
ORDER by action DESC

希望将此商家信息列为最新条目,并在“' action'对于'主题':

id  topic   action  date
3   10127   1   2015-09-24 15:30:01
4   10127   2   2015-09-24 15:30:55
5   10127   3   2015-09-24 16:07:25
6   10127   4   2015-09-24 16:10:25
7   10127   5   2015-09-24 16:29:26

希望有人有解决方案! 谢谢!

3 个答案:

答案 0 :(得分:4)

您可以使用子查询执行此操作。这是完整的sqlfiddle:http://sqlfiddle.com/#!9/f7afa/23

Select * FROM (

SELECT
  DISTINCT  `topic`, `action`, `date`
FROM
  ForgeRock      
ORDER by date DESC, action ASC

  ) as X
  GROUP BY action

答案 1 :(得分:1)

您需要使用子查询:

SELECT *
FROM yourtable
JOIN (
    SELECT topic, MAX(action)
    FROM yourtable
    GROUP BY topic
) AS child ON (yourtable.topic = topic) AND (yourtable.action = child.action)

子查询找到每个主题的最大操作。然后,该数据将用于连接同一个表,您可以使用该表来获取“max'd”记录中的其他字段。

答案 2 :(得分:1)

抱歉,如果没有正确阅读您的问题。这是一个有效的查询:

SELECT id,topic,@action:=@action+1 AS ACTION,DATE
FROM
  ( SELECT t1.id,
           t1.topic,
           t1.date ,
           t2.id AS dup
   FROM tab t1
   LEFT JOIN tab t2 ON t1.action = t2.action
   AND t2.id > t1.id) AS t,

  (SELECT @action:=0) AS tmp
WHERE dup IS NULL;

结果:

+----+-------+--------+---------------------+
| id | topic | ACTION | date                |
+----+-------+--------+---------------------+
|  3 | 10127 |      1 | 2015-09-24 15:30:01 |
|  4 | 10127 |      2 | 2015-09-24 15:30:55 |
|  5 | 10127 |      3 | 2015-09-24 16:07:25 |
|  6 | 10127 |      4 | 2015-09-24 16:10:25 |
|  7 | 10127 |      5 | 2015-09-24 16:29:26 |
+----+-------+--------+---------------------+
5 rows in set (0.00 sec)