0

3 つのテーブル (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    | 
|_______________|___________|______________________|__________|

次のクエリは正常に機能しています (users,forum のみを使用):

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

しかし、このクエリでも3番目のテーブルからいくつかのデータをクエリしようとすると:

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

結果が複製されました (各レコードが複製されました) すべてが正常に表示される理由がわかりません。

4

2 に答える 2

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
于 2013-07-10T13:59:18.480 に答える
-1

最後のコメントを検索したいので、group by functionを使用してください

GROUP BY f1.match_static_id

SQL Fiddle - 便利です

「users.id」列はありません

于 2013-07-10T13:50:09.507 に答える