动态mysql选择stament

时间:2017-01-06 17:35:02

标签: mysql database

我有一张表:

+-----------------------------+
| ID | ID_CONV | NAME | DATA  |
| 1  |    1    | ALEX | DATA1 |
| 2  |    1    | ALEX | DATA2 |
| 3  |    2    | ALEX | DATA3 |
| 4  |    2    | ALEX | DATA4 |
| 5  |    3    | NIKO | DATA5 |
| 6  |    4    | ALEX | DATA6 |
| 7  |    4    | ALEX | DATA7 |
| 8  |    3    | NIKO | DATA8 |
+-----------------------------+

我想选择alex的DATA但只有最大ID_CONV,有些像这样:

+-----------------------------+
| ID | ID_CONV | NAME | DATA  |
| 6  |    4    | ALEX | DATA6 |
| 7  |    4    | ALEX | DATA7 |
+-----------------------------+

目前,要做到这一点,我必须要求最大Alex的ID_CONV,然后用这个ID_CONV选择数据。

我的问题是,是否有可能提高此咨询的效率

2 个答案:

答案 0 :(得分:3)

您可以找到每个名称的最大id_conv,并将其与主表连接,如下所示:

SELECT t.*
FROM your_table t
INNER JOIN
  ( SELECT name, MAX(id_conv) id_conv FROM your_table GROUP BY name
  ) t2
ON t.name     = t2.name
AND t.id_conv = t2.id_conv
WHERE t.name  = 'ALEX';

这是一个(较慢的)相关查询:

SELECT *
FROM your_table t
WHERE t.name = 'ALEX'
AND id_conv IN
  ( SELECT MAX(id_conv) id_conv FROM your_table t2 WHERE t2.name = t.name
  ) ;

答案 1 :(得分:-1)

试试这个:

SELECT ID , MAX(ID_CONV) , NAME , DATA  
  FROM MyTable
 WHERE NAME = 'ALEX'