从连接的第二个表中获取MAX值行

时间:2015-05-08 07:24:45

标签: mysql

我有2个表,第一个保存名称,第二个表位于= cid中。我需要从第二个表中获得一次最高日期行。请看下面更清楚的解释:

table1 a

+----+-------+
| id |  name |
+----+-------+
|  1 | name1 |
|  2 | name2 |
|  3 | name3 |
|  4 | name4 |
|  5 | name5 |
+----+-------+

table2 c

+----+-------+------------+
| id | cid   | galiojaiki |
+----+-------+------------+
|  1 |    1  | 2015-04-30 |
|  2 |    1  | 2015-09-30 |
|  3 |    1  | 2015-03-10 |
|  4 |    2  | 2015-06-30 |
|  5 |    2  | 2015-07-30 |
|  6 |    3  | 2015-05-11 |
|  7 |    4  | 2015-05-10 |
+----+-------+------------+

预期结果:

+------------+-------+
| galiojaiki |  name |
+------------+-------+
| 2015-09-30 | name1 |
| 2015-07-30 | name2 |
| 2015-05-11 | name3 |
| 2015-05-11 | name4 |
+------------+-------+

我的查询:

SELECT a.*, c.galiojaiki FROM `y6fdt_igym_abonementai` AS a 
INNER JOIN 
( 
    SELECT max(galiojaiki) FROM y6fdt_igym_sutartys
) c
on c.cid= a.id
GROUP BY c.abonementas

1 个答案:

答案 0 :(得分:1)

如何使用MAX进行简单聚合?

这样的东西
SELECT a.name, 
MAX(b.galiojaiki) as galiojaiki
FROM `y6fdt_igym_abonementai` AS a INNER JOIN
`y6fdt_igym_sutartys` as b  ON a.ID = b.CID
GROUP BY a.name

SQL Fiddle DEMO