我有下表(简化,删除不需要的列):
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 :(得分: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 :(得分:1)
select t.* from packageTransactions t
join
(
select distinct memberID
from packageTransactions
where subscriptionType = 101
) t1 on t.memberId= t1.memberId
where
(subscriptionType <> 101)