2014-10-18 55 views
0
創建

我有以下SQL查詢它以某種方式打破:選擇數據的SELECT

SELECT * 
FROM (
    SELECT ID, TEST, CHR, NUMBER 
    FROM Test_Table 
    JOIN ... 
    WHERE ... 
) TEMP_TABLE 
FROM TEMP_TABLE a 
LEFT 
JOIN TEMP_TABLE b 
    ON b.test = a.test 
AND b.chr = 'x' 
WHERE a.number IN (5,6) 
AND b.id IS NULL 
GROUP 
    BY a.test 
HAVING COUNT(*) = 2; 

從第一FROM聲明,我得到以下臨時表:

ID , TEST, CHR , NUMBER 
------------------------------ 
(1 , 7 , 'C' ,  5), 
(2 , 7 , 'T' ,  6), 
(3 , 8 , 'C' ,  4), 
(4 , 8 , 'T' ,  5), 
(5 , 9 , 'A' ,  4), 
(6 , 9 , 'G' ,  5), 
(7 , 10 , 'T' ,  4), 
(8 , 10 , 'A' ,  5), 
(9 , 10 , 'X' ,  6), 
(10 , 14 , 'T' ,  4), 
(11 , 14 , 'G' ,  5); 

FROM TEMP_TABLE ...我嘗試實施下列條件:

  1. 例如test第7列包含兩行,如果number列包含值5和6,並且該值不是在chr列中,我想選擇在test列中選擇具有7的行。

  2. 例如test柱10含有三行,如果number列包含值5和6,以及值X存在於chr列中,我想在test柱10以排除行。

至於導致只應test柱7,因爲test第7列有5個和6個在number列,而不是X.

結果例如:

ID | TEST | CHR | NUMBER    
1 | 7 | C | 5   
2 | 7 | T | 6 

做什麼上面的SQL查詢出錯了嗎?

回答

3

您的查詢有兩個FROM條款中刪除一個,並嘗試像下面

SELECT * 
FROM (
    SELECT ID, TEST, CHR, NUMBER 
    FROM Test_Table 
    JOIN ... 
    WHERE ... 
) a 
LEFT JOIN 
(
    SELECT ID, TEST, CHR, NUMBER 
    FROM Test_Table 
    JOIN ... 
    WHERE ... 
) b 
    ON b.test = a.test 
AND b.chr = 'x' 
WHERE a.number IN (5,6) 
AND b.id IS NULL 
GROUP 
    BY a.test 
HAVING COUNT(*) = 2; 

一個更簡單的方式做,這是創建使用TEMPORARY關鍵字TEMPORARY表像提到here

CREATE TEMPORARY TABLE TEMP_TABLE (ID int, TEST varchar(100), CHR char, NUMBER int); 

INSERT INTO TEMP_TABLE 
(SELECT ID, TEST, CHR, NUMBER 
FROM Test_Table 
JOIN ... 
WHERE ...); 


SELECT * 
FROM TEMP_TABLE a 
LEFT 
JOIN TEMP_TABLE b 
    ON b.test = a.test 
AND b.chr = 'x' 
WHERE a.number IN (5,6) 
AND b.id IS NULL 
GROUP 
    BY a.test 
HAVING COUNT(*) = 2;