2012-01-20 260 views
2

我有兩個表格:COURSES和PERMISSIONS。我正在嘗試執行一個SELECT,其中顯示給定帳戶中給定學生的所有現有課程的最新權限值。MySQL選擇最近日期的記錄

現在,我這樣做:

SELECT COURSES.NAME, PERMISSIONS.VALUE, PERMISSIONS.TS 
FROM COURSES LEFT JOIN PERMISSIONS 
ON PERMISSIONS.C_ID = COURSES.C_ID AND PERMISSIONS.S_ID = '12345' 
WHERE COURSES.A_ID = 'ABCDE' 

結果我得到的是

NAME   | VALUE | TS 
----------------------------------------------- 
Mathematics | 1  | 2012-01-19 19:13:21 
Mathematics | 0  | 2012-01-19 19:13:15 
Mathematics | 0  | 2012-01-19 19:20:19 
Mathematics | 0  | 2012-01-19 19:20:27 
Mathematics | 0  | 2012-01-19 19:21:29 
Biology  |   | 

我需要的是隻顯示了最新的時間戳(TS)的記錄,這樣就說明這個:

NAME   | VALUE | TS 
----------------------------------------------- 
Mathematics | 0  | 2012-01-19 19:21:29 
Biology  |   | 

我結合上課程名稱試圖GROUP BYORDER BY在Ti mestamp,但它沒有選擇正確的記錄。

任何人都可以請幫忙嗎?

回答

0
SELECT COURSES.NAME, PL.VALUE, PL.TS 
FROM COURSES 
LEFT JOIN 
    (SELECT 
     PERMISSIONS.C_ID, PERMISSIONS.VALUE, PERMISSIONS.TS 
    FROM PERMISSIONS 
    JOIN 
     (SELECT P.C_ID, MAX(P.TS) AS LATEST 
     FROM PERMISSIONS P 
     WHERE P.S_ID = '12345' 
     GROUP BY P.C_ID) PG 
    ON PERMISSIONS.TS = PG.LATEST) PL 
    ON PL.C_ID = COURSES.C_ID 
WHERE COURSES.A_ID = 'ABCDE' 

根據對於您的數據大小,您可以考慮在PERMISSIONS表中添加(C_ID,TS)索引以加速查找最新日期:

ALTER TABLE `PERMISSIONS` ADD INDEX (`C_ID`,`TS`); 
+0

工作很好!讓我走上正軌。添加到第二個子選擇'WHERE PERMISSIONS.S_ID ='12345'' – greener

2

您需要使用HAVING。因此,它應該被什麼東西是這樣的

SELECT COURSES.NAME, PERMISSIONS.VALUE, PERMISSIONS.TS 
FROM COURSES LEFT JOIN PERMISSIONS 
ON PERMISSIONS.C_ID = COURSES.C_ID AND PERMISSIONS.S_ID = '12345' 
WHERE COURSES.A_ID = 'ABCDE' 
GROUP BY COURSES.A_ID 
HAVING PERMISSIONS.TS = MAX(PERMISSIONS.TS) 

(這將是更容易的表結構)

另一種可能性是認爲它相反的方向。加入本身的權限表,發現沒有一個更高的時間戳

SELECT COURSES.NAME, PA.VALUE, PA.TS 
    FROM COURSES LEFT JOIN PERMISSIONS PA 
    ON PA.C_ID = COURSES.C_ID AND PA.S_ID = '12345' 
    WHERE COURSES.A_ID = 'ABCDE' 
     AND (PA.C_ID == NULL || NOT EXISTS (
      SELECT * 
      FROM PERMISSIONS PB 
      WHERE PA.C_ID = PB.C_ID AND PB.S_ID = '12345' AND PB.TS > PA.TS)) 
+0

我嘗試了兩種選擇,但結果並不如預期。例如,HAVING選項不返回任何記錄。 – greener

+0

Mhhh在HAVING中可能有錯誤。另一方面,你看到了什麼問題?多個數學系或沒有生物學(實際上,是的,我錯過了空例) – Luis

0

另一種選擇許可 - 一個子查詢計算權限表的最大時間戳:

SELECT courses.name, x.value, x.timestamp 
FROM courses 
LEFT JOIN (SELECT p1.c_id, p1.s_id, p1.value, p1.timestamp 
    FROM permissions p1 
    LEFT JOIN permissions p2 ON p1.c_id = p2.c_id AND p1.s_id = p2.s_id AND p1.timestamp < p2.timestamp 
    WHERE p2.timestamp IS NULL) x ON courses.c_id = x.c_id AND x.s_id = '12345' 
WHERE courses.a_id = 'ABCDE'