2014-03-27 58 views
0

好的,所以有3個元素來自我用於查詢的數據庫。Mysql - 是否有更好的方式來運行大量數據的子查詢?

人,用爲person_id作爲主鍵,

Learners_to_classes,以擁有自己的主鍵和兩個外鍵,以及類標識碼PERSON_ID

和類具有一個主鍵類標識碼。

Learners_to_classes有許多與人,班,怎麼過了兩個外鍵都必須是唯一的(人不能參加同等級的兩倍多的關係。

每個類都有自己的COURSE_ID(定義什麼類型一流的,它是)。

有4萬多條記錄learners_to_classes, 超過36000條記錄的人, 和大約1,300記錄類。

我所要做的,就是算人誰做了一種類型的合作但不是其他人。

SELECT count(distinct ltc.person_id) AS participants, 
     classes.classcode as classcode, 
     DATE_FORMAT(classes.course_start_date, '%Y') AS YEARPeriod 
FROM learners_to_classes AS ltc 
INNER JOIN classes ON ltc.class_id = classes.class_id 
WHERE classes.deleted=0 
AND classes.course_id=1 
AND NOT EXISTS (SELECT * 
       FROM learners_to_classes AS o 
       INNER JOIN classes AS c ON o.class_id=c.class_id 
       WHERE (c.course_id=2 OR c.course_id=4) 
       AND o.person_id=ltc.person_id) 
GROUP BY YEAR(classes.course_start_date), classcode 

此查詢需要長時間運行過一個地獄,我希望有可能是一個更有效的方式來獲取信息。

回答

0

大概你想要的人選了課程1但不是課程4.你可以用聚合查詢和having子句做到這一點。下面的查詢返回誰採取一個類而不是其他學習者:

SELECT ltc.person_id 
FROM learners_to_classes AS ltc INNER JOIN 
    classes c 
    ON ltc.class_id = c.class_id 
WHERE c.deleted = 0 
GROUP BY ltc.person_id 
HAVING sum(c.course_id = 1) = 1 and 
     sum(c.course_id = 4) = 0; 

如果你想這樣的人只是數量,以此作爲一個子查詢:

SELECT COUNT(*) 
FROM (SELECT ltc.person_id 
     FROM learners_to_classes AS ltc INNER JOIN 
      classes c 
      ON ltc.class_id = c.class_id 
     WHERE c.deleted = 0 
     GROUP BY ltc.person_id 
     HAVING sum(c.course_id = 1) = 1 and 
      sum(c.course_id = 4) = 0 
    ) l; 
+0

這正是我需要。非常感謝你! – Lars

相關問題