我有这个查询,但它花费的时间太长,通过 NaviCat 大约需要 30 秒。如果可能的话如何优化?
SELECT DISTINCT c.clientid, c.name, c.email, c.region
FROM clients c RIGHT JOIN orders o ON c.clientid = o.clientid
WHERE o.order_status = 'pending'
AND c.clientid NOT IN (
SELECT DISTINCT c.clientid
FROM clients c, orders o
WHERE c.clientid = o.clientid AND o.order_status = 'paid'
)
ORDER BY c.id DESC
为了更好地了解我的需要:我有 2 个表:
clients (id, clientid, name, email, region)
orders (id, orderid, clientid, order_amount, order_status, ….)
记录示例:
Client | Order | Status
-----------------------
C1 | O1 | (paid)
C1 | O2 | (pending)
C2 | O3 | (paid)
C3 | O4 | (pending)
C4 | O5 | (paid)
C5 | O6 | (pending)
我只需要返回C3
和C5
非常感谢您的回答。
最佳答案
方法有很多,这里是其中一个技巧:-
SELECT c.clientid, c.name, c.email, c.region,
SUM(IF(o.order_status = 'paid', 1, 0)) as paid
FROM clients c
INNER JOIN orders o
ON c.clientid = o.clientid
WHERE o.order_status IN( 'pending', 'paid')
GROUP BY c.clientid
HAVING paid = 0;
关于mysql - 我应该如何优化这个mysql查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8508264/