2011-08-11 75 views
0

我有2個表。 Person桌子和activity_log桌子mysql表加入集合

每個人都有很多活動。

我想「選擇」顯示他們上一次活動的activity_name和activity_date的「persons」列表。 (不是所有的活動)

Person表已經PERSON_ID,姓名,電子郵件

活動表已PERSON_ID,ACTIVITY_ID,activity_date,ACTIVITY_NAME

感謝您的幫助提前。

回答

1

子查詢應該做的伎倆:

SELECT p.person_id, p.name, p.email, a.activity_id, a.activity_date, a.activity_name 
FROM Person p 
LEFT JOIN Activity a 
ON p.person_id = a.person_id 
WHERE a.activity_date = (SELECT MAX(a1.activity_date) 
       FROM activity a1 
       WHERE a.person_id = a1.person_id 
       GROUP BY person_id) OR activity_date IS NULL; 
+0

這僅返回1行,仍然必須證明員工或開展活動 – user583576

+0

讓我們嘗試了'LEFT JOIN'這裏,而不是一個'INNER JOIN'。我會編輯。 – NickHeidke

+0

仍然只返回最高日期的1行 – user583576

1

假設你的ID是自動編號,你會做這樣的:

SELECT pe.person_id, 
     pe.name, 
     al.activity_name, 
     al.activity_date 
FROM person pe 
     LEFT JOIN (SELECT p.person_id, 
         Max(a.activity_id) activity_id 
        FROM person p 
         LEFT JOIN activity_log a 
          ON (p.person_id = a.person_id) 
        GROUP BY p.person_id) AS LAST 
     ON pe.person_id = LAST.person_id 
     LEFT JOIN activity_log al 
     ON LAST.activity_id = al.activity_id 

然而,用戶可能會比新進入後過去的活動,那麼這將失敗,你不得不去這樣:

SELECT LAST.person_id, 
     LAST.name, 
     LAST.activity_date, 
     (SELECT activity_name 
     FROM activity_log al 
     WHERE al.person_id = LAST.person_id 
       AND al.activity_date = LAST.activity_date) activity_name 
FROM (SELECT p.person_id, 
       Max(p.name)   AS name, 
       Max(a.activity_date) activity_date 
     FROM person p 
       LEFT JOIN activity_log a 
       ON (p.person_id = a.person_id) 
     GROUP BY p.person_id) AS LAST 

但是,這仍然有一個問題:因爲MySQL不允許在子查詢LIMIT,查詢會是同一個人有相同activity_date兩項活動失敗,這是最新的日期。