2012-12-20 28 views
1

我有如下表(簡化,去除不必要的列):嵌套MySQL查詢中的優化可能嗎?

packageTransactions

| memberID | subscriptionType | 
| ==========|===================| 
| 12345  | 101    | 
| 12345  | 203    | 
| 12346  | 101    | 
| 12347  | 101    | 
| 12348  | 101    | 
| 12348  | 203    | 
| 12349  | 203    | 
| 12345  | 205    | 

我要查詢哪些具有subscriptionType = 101,但只有那些所有記錄subscriptionType = 101的記錄存在相同的memberID

因此,我用:

SELECT memberID, subscriptionType 
    FROM packageTransactions 
WHERE memberID IN 
    (SELECT memberID 
     FROM packageTransactions 
     WHERE subscriptionType = '101' 
    ) 
    AND subscriptionType <> '101' 
; 

這給了我,我要找的結果集:

| memberID | subscriptionType | 
| ==========|===================| 
| 12345  | 203    | 
| 12348  | 203    | 
| 12345  | 205    | 

然而,在使用上表這個查詢與幾個thousend記錄時( + 30k在我的情況下),它需要幾分鐘才能返回結果。

所以我想知道,如果有一個「更好」 /更有效的方式來查詢數據?

+0

SELECT MEMBERID,subscriptionType FROM packageTransactions WHERE subscriptionType = '101'!。你試過這個爲什麼你在哪裏使用? –

+0

對不起,英語不是我的母語。我試圖在現在的問題中更加明確。因爲我只想得到那些'memberID',其中'subscriptionType' ='101'的記錄通常也存在。例如,memberID 12349應該不會被返回,因爲它沒有'subscriptionType' ='101'的記錄。 – eyecatchUp

回答

1

試試這個:

SELECT pt2.memberID, pt2.subscriptionType 
FROM packageTransactions pt1 inner join packageTransactions pt2 
    ON pt1.memberID = pt2.memberID 
WHERE 
    pt1.subscriptionType = '101' AND pt2.subscriptionType <> '101' 

; 
1

這裏是一個SQLFiddle demo

select t.* from packageTransactions t 
join 
(
    select distinct memberID 
    from packageTransactions 
    where subscriptionType = 101 
) t1 on t.memberId= t1.memberId 
where 
    (subscriptionType <> 101) 
+0

謝謝。你和Omar的解決方案都要快得多。但是,現在我想知道哪個查詢更合適,對我而言更重要 - 爲什麼? – eyecatchUp