2014-01-25 107 views
-2

我在SQL新手和有問題希望你能幫助我:如何查詢SQL交叉引用表

MYSQL5

表TRAINING_REQUESTS

 
+------------+--------+ 
| ID_TR | FIELD | 
+------------+--------+ 
|  ... | .. | 
|  254 | .. | 
|  ... | .. | 
|  286 | .. | 
|  ... | .. | 
|  401 | .. | 
|  ... | .. | 
|  405 | .. | 
|  406 | .. | 
|  ... | .. | 
+------------+--------+ 

表PLANNING_REQUESTS

 
+----------+----------+----------+ 
| ID_PR | ID_TR | TRAINER | 
+----------+----------+----------+ 
|  ... | ...  | ...  | 
|  475 | 254  | NULL | 
|  476 | 254  | NULL | 
|  477 | 254  | NULL | 
|  478 | 286  | NULL | 
|  479 | 286  | FREE | 
|  480 | 286  | FREE | 
|  481 | 401  | FREE | 
|  482 | 401  | 1  | 
|  483 | 401  | FREE | 
|  484 | 405  | NULL | 
|  485 | 405  | 1  | 
|  486 | 405  | 5  | 
|  487 | 405  | FREE | 
|  488 | 406  | 1  | 
|  489 | 406  | 5  | 
|  490 | 406  | 5  | 
|  491 | 406  | 2  | 
|  ... | ...  | ...  | 
+----------+----------+----------+ 

我需要三樣東西:

預期結果

約束:所有training_requests(ID_TR)是不正常,這意味着 (>>已分配的所有規劃要求所有培訓請求(ID_TR) (ID_PR) 與教練的equals(null或FREE)

 
+------------+-------+ 
| ID_TR | field | 
+------------+-------+ 
|  254 | .. | 
|  286 | .. | 
+------------+-------+ 

約束:所有training_requests(ID_TR)是幾乎確定,這意味着已分配的所有 (>>所有訓練要求(ID_TR)規劃要求(ID_PR) 與教練至少一次不同FROM(null或FREE) ,而不是所有與教練ASSIGNED(不同於null或免費)

 
+------------+-------+ 
| ID_TR | FIELD | 
+------------+-------+ 
|  405 | .. | 
+------------+-------+ 

約束:一切都沒有確定的training_requests和幾乎可以

 
+------------+------+ 
| ID_TR |FIELD | 
+------------+------+ 
|  405 | .. | 
|  254 | .. | 
|  286 | .. | 
+------------+------+ 

thx for all!

+0

你試過寫你的查詢嗎? –

+0

ofc我試過,但即時通訊初學者在SQL和我不知道如何查詢交叉引用表 – juhnz

+0

你知道'JOIN'是什麼?或'EXISTS'? –

回答

0
SELECT tr.ID_TR,tr.field 
    FROM planning_requests pr 
    INNER JOIN training_requests tr 
    ON tr.ID_TR = pr.ID_TR 
    WHERE pr.ID_TR NOT IN 
     (
     SELECT cpr.ID_TR 
     FROM planning_requests cpr 
     WHERE trainer IS NOT NULL AND trainer <> 'FREE' 
    ) 
    GROUP BY ID_TR 
0

這是可以做到以下(可能是低效的)方式:

#1也不行

SELECT tr.* 
FROM TRAINING_REQUESTS tr 
JOIN PLANNING_REQUESTS pr ON tr.id_tr = pr.id_tr 
GROUP BY pr.id_tr 
HAVING SUM(CASE WHEN pr.trainer IS NULL or pr.trainer = 'FREE' THEN 1 ELSE 0 END) = COUNT(*) 
; 

#2近OK

SELECT tr.* 
FROM TRAINING_REQUESTS tr 
WHERE EXISTS (SELECT 1 
       FROM PLANNING_REQUESTS pr 
       WHERE tr.id_tr = pr.id_tr 
       AND pr.trainer IS NOT NULL AND pr.trainer <> 'FREE') 
    AND EXISTS (SELECT 1 
       FROM PLANNING_REQUESTS pr 
       WHERE tr.id_tr = pr.id_tr 
       AND (pr.trainer IS NULL OR pr.trainer = 'FREE'))   
; 

#3

SELECT tr.* 
    FROM TRAINING_REQUESTS tr 
    WHERE EXISTS (SELECT 1 
        FROM PLANNING_REQUESTS pr 
        WHERE tr.id_tr = pr.id_tr 
        AND (pr.trainer IS NULL OR pr.trainer = 'FREE'))   
; 

這裏的SQL Fiddle的結果。

請注意,我在#2(因此#3)中的結果與您的結果不同,因爲它們包括。