SELECT DISTINCT和CONCAT不会正确返回值

时间:2015-06-05 16:43:45

标签: mysql sql select distinct concat

我有一个带有此值的数据库:

CREATE TABLE test (
Id CHAR (50),
Time TIMESTAMP ,
Value CHAR (50)
);

INSERT INTO test VALUES ('JOE', '2015-06-05 15:36:21', "ZONE1");
INSERT INTO test VALUES ('ANNA', '2015-06-05 14:27:35', "ZONE2");
INSERT INTO test VALUES ('JOE','2015-06-05 16:27:36', "ZONE2");
INSERT INTO test VALUES ('ANNA', '2015-06-05 14:45:31',"ZONE1");
INSERT INTO test VALUES ('JOE','2015-06-05 11:12:31', "ZONE4");
INSERT INTO test VALUES ('ANNA', '2015-06-05 10:25:21',"ZONE3");

我想在最后一个区域找到用户

我尝试使用这个SQL intruction:

SELECT DISTINCT(Id), MAX(Time) AS Time,
CONCAT('{ "Time":"', DATE_FORMAT(Time, '%Y-%e-%d %h:%i:%s'), '", "ID":"',     CAST(Id AS CHAR), '", "Zone":"', Value, '" }') json
FROM test
GROUP BY Id;

但是,这是回报:

|   Id |                   Time |                                                         json |

|------|------------------------|----------------------------------------------------------------------------------------------|

| ANNA | June, 05 2015 14:45:31 | { "Time":"2015-5-05 02:27:35", "ID":"ANNA", "Zone":"ZONE2" } |

|  JOE | June, 05 2015 16:27:36 |  { "Time":"2015-5-05 03:36:21", "ID":"JOE", "Zone":"ZONE1" } |

我不明白为什么.....这是不同日期无序的回报  在第三列...

谢谢!

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的问题你想做这样的事情:

  SELECT Id, Time,
         CONCAT('{ "Time":"', DATE_FORMAT(Time, '%Y-%e-%d %h:%i:%s'), '", "ID":"', CAST(Id AS CHAR), '", "Zone":"', Value, '" }') json
  FROM (SELECT * 
        FROM test 
        ORDER BY Time DESC) as t
  GROUP BY Id;

以下是SQL Fiddle,了解它是如何运作的......

GL!

PS (编辑)你不需要在他们做同样的工作的同时使用DISTINCT和GROUP BY功能......他们也选择了第一行中的值如果你想从你有一些价值的行中选择值(比如你的MAX(时间)),那么你只需将它放在排序的顶部。我在这个子查询中做到了

(SELECT * 
 FROM test 
 ORDER BY Time DESC) as t

编辑:嗨,再次,Andriy在评论中的建议我发现我的第一个答案并不是解决这个问题的最佳方法。所以,感谢Andriy,我带来了更好更安全的解决方案。

第一个是相关子查询:

SELECT Id, Time,
       CONCAT('{ "Time":"', DATE_FORMAT(Time, '%Y-%e-%d %h:%i:%s'), '", "ID":"', CAST(Id AS CHAR), '", "Zone":"', Value, '" }') json
FROM test t1
WHERE Time = (SELECT MAX(t2.Time)
              FROM test t2
              WHERE t1.id = t2.id);

第二个不相关的子查询:

 SELECT t1.Id, t1.Time,
       CONCAT('{ "Time":"', DATE_FORMAT(t1.Time, '%Y-%e-%d %h:%i:%s'), '", "ID":"', CAST(t1.Id AS CHAR), '", "Zone":"', t1.Value, '" }') json
 FROM test t1
 INNER JOIN (SELECT id, MAX(Time) AS Time
             FROM test
             GROUP BY id) AS t2
 ON t1.id = t2.id AND t1.Time = t2.Time;

关于这一点的更多信息,你可以阅读here,有三种方法可以解决这类问题,我为你写了第一种和第二种方式的查询,让你让LEFT JOIN与它玩一点:)

here is SQL Fiddle了解这个新解决方案的工作原理。

再次归功于Andriy M的建议,即使用Group by和Order子句并不聪明......

GL!