可以在嵌套MySQL查询中进行优化吗?
我简化了下表,删除了不需要的列: 包装交易 我想查询所有没有subscriptionType=101的记录,但只查询那些存在相同memberID的subscriptionType=101记录的记录 因此,我使用:可以在嵌套MySQL查询中进行优化吗?,mysql,Mysql,我简化了下表,删除了不需要的列: 包装交易 我想查询所有没有subscriptionType=101的记录,但只查询那些存在相同memberID的subscriptionType=101记录的记录 因此,我使用: SELECT memberID, subscriptionType FROM packageTransactions WHERE memberID IN ( SELECT memberID FROM packageTransactions W
SELECT memberID, subscriptionType
FROM packageTransactions
WHERE memberID IN
( SELECT memberID
FROM packageTransactions
WHERE subscriptionType = '101'
)
AND subscriptionType <> '101'
;
但是,在我的例子中,当对具有几千条记录+30k的表使用此查询时,返回结果需要几分钟
所以我想知道,是否有更好/更有效的方法来查询数据?试试这个:
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'
;
这是一个
从packageTransactions中选择memberID、subscriptionType,其中subscriptionType!='101'. 你试过了吗?为什么用where in?对不起,英语不是我的母语。我现在试图在问题中说得更清楚些。因为我只想获取那些MemberID,其中通常还存在subscriptionType='101'的记录。例如,不应返回memberID 12349,因为它没有subscriptionType='101'的记录。谢谢。您的和奥马尔的解决方案都大大加快了速度。然而,现在我想知道哪一个问题更合适,而且——对我来说更重要——为什么?
| memberID | subscriptionType |
| ==========|===================|
| 12345 | 203 |
| 12348 | 203 |
| 12345 | 205 |
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'
;
select t.* from packageTransactions t
join
(
select distinct memberID
from packageTransactions
where subscriptionType = 101
) t1 on t.memberId= t1.memberId
where
(subscriptionType <> 101)