2013-07-10 62 views
0

我有三个表(MySQL的):三用聚合函数问题加入

matches: 
___________________________ 
|match_static_id| team_name | 
|_______________|___________| 
| 1   | Italy | 
| 2   | France | 
|_______________|___________| 

users: 
___________________________ 
|user_id  | username | 
|_______________|___________| 
| 1   | Dolly | 
| 2   | Didi  | 
|_______________|___________| 

forum: 
_____________________________________________________________ 
|match_static_id| comment | timestamp   | user_id | 
|_______________|___________|______________________|__________| 
| 1   | Hi  | 2013-07-10 12:15:03 |  2 | 
| 1   | Hello | 2013-07-09 12:14:44 |  1 | 
|_______________|___________|______________________|__________| 

下面的查询工作正常(仅使用用户,论坛):

SELECT f1.match_static_id, 
    f2.comments_no, 
    f2.maxtimestamp, 
    users.username 
FROM forum AS f1 

INNER JOIN 
(
    SELECT match_static_id, 
    max(timestamp) maxtimestamp, 
    count(match_static_id) AS comments_no 
    FROM forum 
    GROUP BY match_static_id 
) AS f2 ON f1.match_static_id = f2.match_static_id 
     AND f1.timestamp = f2.maxtimestamp 
INNER JOIN users on users.user_id = f1.user_id 
Order BY f2.maxtimestamp DESC 

但是,当我尝试查询来自第三个表的一些数据也使用此查询:

SELECT f1.match_static_id, 
    f2.comments_no, 
    f2.maxtimestamp, 
    users.username, 
    matches.team_name 
FROM forum AS f1 

INNER JOIN 
(
    SELECT match_static_id, 
    max(timestamp) maxtimestamp, 
    count(match_static_id) AS comments_no 
    FROM forum 
    GROUP BY match_static_id 
) AS f2 ON f1.match_static_id = f2.match_static_id 
     AND f1.timestamp = f2.maxtimestamp 
INNER JOIN users on users.id = f1.user_id 
INNER JOIN matches on matches.match_static_id = f2.match_static_id 
Order BY f2.maxtimestamp DESC 

结果重复(每条记录重复)I不要为什么我看到一切正常 所以如果有人有任何想法,可以帮助我请帮助!

+0

这将是我们更容易帮助你,如果你设置了[SQL小提琴(http://sqlfiddle.com/) –

+0

您正在使用什么版本的MySQL?你的第二个例子似乎工作正常(固定列名后),或者至少只返回一行。 [SQLFiddle](http://sqlfiddle.com/#!2/eca1a/5/0) –

+0

我尝试使SQLFiddle和一切工作正常,但在我的数据库上工作时,结果重复 – Basel

回答

-1

我想,你要搜索最后的评论,所以只需按功能使用组

GROUP BY f1.match_static_id

SQL小提琴 - 将是有益的

并没有“users.id “collumn

0

您可能不需要在内部select语句上执行连接。

SELECT 
    f1.match_static_id, 
    count(f1.comment) as comments_no, 
    max(timestamp) as maxtimestamp, 
    users.username, 
    matches.team_name 
FROM 
    forum AS f1 
INNER JOIN users u on u.id = f1.user_id 
INNER JOIN matches m on m.static_id = f1.match_static_id 
GROUP BY m.match_static_id 
ORDER BY maxtimestamp DESC