MySQL将SELECT结果排成行

时间:2015-01-22 15:30:02

标签: mysql

假设我有两张相同的表格,如下:

table1              table2
+--------+------+   +--------+------+
| fruit  | year |   | fruit  | year |
+--------+------+   +--------+------+
| apple  | 2015 |   | apple  | 2014 |
| banana | 2014 |   | apple  | 2013 |
| banana | 2013 |   | banana | 2011 |
+--------+------+   +--------+------+   

我想在每张桌子上获得最后一年的成果如下:

+--------+---------+---------+
| fruit  | t1.last | t2.last |
+--------+---------+---------+
| apple  |   2015  |   2014  |
| banana |   2014  |   2011  |
+--------+---------+---------+

对于单个表,可以使用简单的SELECT语句:

SELECT fruit, max( year ) AS last FROM table1 GROUP BY fruit
result:
+--------+------+
| fruit  | last |
+--------+------+
| apple  | 2015 |
| banana | 2014 |
+--------+------+

我不知道的是如何将去年第二张桌子中的每一个水果“附加”作为相邻的一行。

2 个答案:

答案 0 :(得分:2)

SELECT t1.fruit, max(t1.year ) AS t1last, max(t2.year ) AS t2last 
FROM table1 t1, table2 t2 WHERE t1.fruit = t2.fruit GROUP BY t1.fruit

试试

答案 1 :(得分:2)

只有JOIN两个表格。

SELECT fruit,
    max(t1.year) AS `t1.last`,
    max(t2.year) AS `t2.last`
FROM table1 AS t1
JOIN table2 AS t2 USING(fruit)
GROUP BY fruit

DEMO:http://www.sqlfiddle.com/#!2/f3b71/1