2009-08-06 25 views
0

我有一个带时间戳字段'bar'的表'foo'。我怎样才能得到像这样的查询最老的时间戳:SELECT foo.bar from foo?我试着做这样的事情:从foo中选择MIN(foo.bar),但它失败并出现此错误有关特定MySQL查询的帮助:如何从一组数值中获得最小值

错误1140(42000)在行1:混合GROUP列(MIN(),MAX(),COUNT() ,...)没有GROUP列是非法的,如果没有GROUP BY子句

好的,所以我的查询比这更复杂,这就是为什么我很难与它。这是查询与MIN(a.timestamp):

select distinct a.user_id as 'User ID', 
     a.project_id as 'Remix Project Id', 
     prjs.based_on_pid as 'Original Project ID', 
     (case when f.reasons is NULL then 'N' else 'Y' end) 
     as 'Flagged Y or N', 
     f.reasons, f.timestamp, MIN(a.timestamp) 
from view_stats a 
    join (select id, based_on_pid, user_id 
        from projects p) prjs on 
    (a.project_id = prjs.id) 
    left outer join flaggers f on 
    ( f.project_id = a.project_id 
     and f.user_id = a.user_id) 
where a.project_id in 
(select distinct b.id 
    from projects b 
    where b.based_on_pid in 
       (select distinct c.id 
        from projects c 
        where c.user_id = a.user_id 
       ) 
) 
order by f.reasons desc, a.user_id, a.project_id; 

任何帮助将不胜感激。

的view_stats表:

+------------+------------------+------+-----+-------------------+----------------+ 
| Field  | Type    | Null | Key | Default   | Extra   | 
+------------+------------------+------+-----+-------------------+----------------+ 
| id   | int(10) unsigned | NO | PRI | NULL    | auto_increment | 
| user_id | int(10) unsigned | NO | MUL | 0     |    | 
| project_id | int(10) unsigned | NO | MUL | 0     |    | 
| ipaddress | bigint(20)  | YES | MUL | NULL    |    | 
| timestamp | timestamp  | NO |  | CURRENT_TIMESTAMP |    | 
+------------+------------------+------+-----+-------------------+----------------+ 

更新

Based on thomas' suggestion I converted my query to: 
select distinct a.user_id as 'User ID', 
     a.project_id as 'Remix Project Id', 
     prjs.based_on_pid as 'Original Project ID', 
     (case when f.reasons is NULL then 'N' else 'Y' end) 
     as 'Flagged Y or N', 
     f.reasons, f.timestamp, min(a.timestamp) 
from view_stats a 
    join (select id, based_on_pid, user_id 
        from projects p) prjs on 
    (a.project_id = prjs.id) 
    left outer join flaggers f on 
    ( f.project_id = a.project_id 
     and f.user_id = a.user_id) 
where a.project_id in 
(select distinct b.id 
    from projects b 
    where b.based_on_pid in 
       (select distinct c.id 
        from projects c 
        where c.user_id = a.user_id 
       ) 
) 
group by a.project_id, a.user_id 
order by a.timestamp 
; 

它现在运行。

回答

1

如果你打算使用集合函数(如min(),max(),avg()等),你需要告诉数据库到底需要做什么min()。

transaction date 
one   8/4/09 
one   8/5/09 
one   8/6/09 
two   8/1/09 
two   8/3/09 
three   8/4/09 

我想你想要以下内容。

transaction date 
one   8/4/09 
two   8/1/09 
three   8/4/09 

然后让你可以使用下面的查询......注意by子句告诉数据库如何分组的数据组,并得到的东西分钟()。

select 
    transaction, 
    min(date) 
from 
    table 
group by 
    transaction 
+0

谢谢,您的评论帮助我重新思考我的查询。 – amh 2009-08-09 05:22:04