我正在进行自我加入,并且我有以下查询:
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 |
+-----------------------------------------------------------------------+
答案 0 :(得分: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
你会得到这个:
+----+---------------+------------+-------+-----------------------+ | 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 | +----+---------------+------------+-------+-----------------------+
只需选择您感兴趣的字段即可。