0

我正在做一个自我加入,我有以下查询:

select 
    max( wf1.id ) as latest_id, 
    max( wf1.created ) as latest_created, 
    wf1.id, wf1.created, wf1.title,
    wf2.id, wf2.created, wf2.title
from
    worksheet_forms wf1
join
    worksheet_forms wf2
on
    max( wf1.id ) = wf2.id
where 
    wf1.company_id = '000002'
group by 
    wf1.generated_id

但我收到一个错误:

MySQL said: 

#1111 - Invalid use of group function 

我正在尝试做的是获取表中组的最新记录的标题。

编辑:

+-----------------------------------------------------------------------+
|  id |   generated_id  |  company_id  |  title  |      created         |
+-----------------------------------------------------------------------+
|  1  |  aaajdfie34343  |    000002    |   ws1   | 2012-02-08 17:27:30  |
|  2  |  aaajdfie34343  |    000002    |   ws2   | 2012-02-09 17:27:30  |
|  3  |  aaajdfie34343  |    000002    |   ws3   | 2012-02-10 17:27:30  |
|  4  |  bbbjdfie34343  |    000002    |   ws4   | 2012-02-11 17:27:30  |
|  5  |  bbbjdfie34343  |    000002    |   ws5   | 2012-02-12 17:27:30  |
|  6  |  bbbjdfie34343  |    000002    |   ws6   | 2012-02-13 17:27:30  |
|  7  |  bbbjdfie34343  |    000002    |   ws7   | 2012-02-14 17:27:30  |
|  8  |  cccjdfie34343  |    000002    |   ws8   | 2012-02-15 17:27:30  |
|  9  |  cccjdfie34343  |    000002    |   ws9   | 2012-02-16 17:27:30  |
+-----------------------------------------------------------------------+

现在,我想要一个结果:

+-----------------------------------------------------------------------+
|  id |   generated_id  |  company_id  |  title  |      created         |
+-----------------------------------------------------------------------+
|  3  |  aaajdfie34343  |    000002    |   ws3   | 2012-02-10 17:27:30  |
|  7  |  bbbjdfie34343  |    000002    |   ws7   | 2012-02-14 17:27:30  |
|  9  |  cccjdfie34343  |    000002    |   ws9   | 2012-02-16 17:27:30  |
+-----------------------------------------------------------------------+
4

1 回答 1

0

太好了,这更容易理解。运行这个:

select t1.* from t t1
left join t t2
on t1.generated_id = t2.generated_id and t1.created < t2.created
where t2.created is null

你会得到这个:

+----+----------------+------------+-------+------- ----------------+
| 身份证 | GENERATED_ID | COMPANY_ID | 标题 | 创建 |
+----+----------------+------------+-------+------- ----------------+
| 3 | aaaajdfie34343 | 000002 | WS3 | 2012-02-10 17:27:30 |
| 7 | bbbjdfie34343 | 000002 | WS7 | 2012-02-14 17:27:30 |
| 9 | cccjdfie34343 | 000002 | ws9 | 2012-02-16 17:27:30 |
+----+----------------+------------+-------+------- ----------------+

只需选择您感兴趣的领域。

于 2012-04-10T05:57:53.880 回答