1

您好,我的 MYSQL 查询需要帮助

我有桌子

id | tn   | title    | customer_id |create_time | comment              |
1  | 1342 | sample1  | customer1   | 2012-01-01 | hello world          |
2  | 1342 | sample1  | customer1   | 2012-01-02 | hello world          |
3  | 1342 | sample1  | customer1   | 2012-01-03 | hello new world      |
4  | 3362 | sample2  | customer1   | 2012-01-02 | good bye world       |
5  | 3362 | sample2  | customer1   | 2012-01-03 | good bye world       |
6  | 3362 | sample2  | customer1   | 2012-01-04 | good bye world       |
7  | 3362 | sample2  | customer1   | 2012-01-05 | good bye new world   |

当我按 tn 分组时,我采取了

1  | 1342 | sample1  | customer1   | 2012-01-01 | hello world          |
4  | 3362 | sample2  | customer1   | 2012-01-02 | good bye world       |

但我需要采取

3  | 1342 | sample1  | customer1   | 2012-01-03 | hello new world      |
7  | 3362 | sample2  | customer1   | 2012-01-05 | good bye new world   |

这就像按 tn 分组,具有最大 id 或最大 create_time

我怎样才能做到这一点?谢谢!

4

3 回答 3

2

尝试这个:

mysql> select * from ( select * from tbl2 tn order by id desc ) t group by tn;
+------+------+---------+-------------+-------------+--------------------+
| id   | tn   | title   | customer_id | create_time | comment            |
+------+------+---------+-------------+-------------+--------------------+
|    3 | 1342 | sample1 | customer1   | 2012-01-03  | hello new world    |
|    7 | 3362 | sample2 | customer1   | 2012-01-05  | good bye new world |
+------+------+---------+-------------+-------------+--------------------+
2 rows in set (0.02 sec)
于 2012-06-29T21:10:41.320 回答
1
SELECT t2.* FROM
(SELECT MAX(id) AS id,tn FROM my_table GROUP BY tn) AS t1
LEFT JOIN my_table AS t2 USING(id)
于 2012-06-29T21:07:31.723 回答
0

尝试这个

Select t.* from 
table t right join
(Select max(id) as max_id from table group by tn) t1 on (t.id=t1.max_id)
于 2012-06-29T21:09:36.090 回答