1

我有 2 张桌子

`timezone_detail` (
     `timezone_detail_id` INT(11) NOT NULL AUTO_INCREMENT,
     `abbreviation` VARCHAR(6) DEFAULT NULL,
     `time_start` BIGINT(11) DEFAULT NULL,
     `time_zone_id` INT(11) DEFAULT NULL
 )
 `time_zone` (                                    
     `time_zone_id` INT(10) NOT NULL AUTO_INCREMENT,
     `timezone_name` VARCHAR(100) DEFAULT NULL,
     `country_code` VARCHAR(5) DEFAULT NULL
  ) 

我将查询应用为

SELECT z.country_code,tz.abbreviation,tz.time_start
FROM `time_zone` z
 LEFT JOIN `timezone_detail` tz ON z.time_zone_id = tz.time_zone_id

country_code    abbreviation    time_start
AE                LMT          -2147483648
AE                LMT          -2147397248
AE                GST          -1577936472
AF                AFT          -2147483648
AF                AFT          -2147397248
AF                AFT          -788932800
IN                IST          -872058600
IN                IST          -862637400
IN                IST          -764145000


after using **GROUP BY tz.country_code** it gives all first record as
AE  LMT -2147483648
AF  AFT -2147483648
IN  IST -872058600

but I want records with maximum time_start in each group as 

AE  GST -1577936472
AF  AFT -788932800
IN  IST -764145000

请帮助找到这些记录。谢谢

4

2 回答 2

0

询问:

   SELECT z.country_code,
          tz.abbreviation,
          tz.time_start
   FROM time_zone z 
   LEFT JOIN timezone_detail tz ON z.time_zone_id = tz.time_zone_id
   JOIN (SELECT z.country_code, tz.abbreviation, MAX(tz.time_start) time_start
         FROM time_zone z 
         LEFT JOIN timezone_detail tz ON z.time_zone_id = tz.time_zone_id
         GROUP BY z.country_code, tz.abbreviation ) a
    ON z.country_code = a.country_code 
          tz.abbreviation =a.abbreviation 
          tz.time_start = a.time_start 
于 2013-11-07T10:10:05.623 回答
0

使用have子句:

SELECT z.country_code, tz.abbreviation, MIN(tz.time_start) as time_start
    FROM time_zone z LEFT JOIN timezone_detail tz ON z.time_zone_id = tz.time_zone_id
    GROUP BY tz.country_code HAVING MIN(tz.time_start)
于 2013-11-07T10:01:12.083 回答