mysql - 我应该如何优化这个mysql查询?

标签 mysql optimization join

我有这个查询,但它花费的时间太长,通过 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)

我只需要返回C3C5

非常感谢您的回答。

最佳答案

方法有很多,这里是其中一个技巧:-

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/

相关文章:

mysql - 如何在本地主机上查找 MySQL ip?

optimization - Logger slf4j 使用 {} 格式化而不是字符串连接的优点

甲骨文 : how to ensure that a function in the where clause will be called only after all the remaining where clauses have filtered the result?

MySQL 在第二次 JOIN 时抛出错误

php - 使用 OR 子句的 SQL 查询

mysql - 过滤一对多关系查询结果的最佳方式。 MySQL

mysql - 将两个查询组合成单半径搜索以进行映射

mysql - 查询导致另一表中的一行的多行

Mysql数据库设计多值多值

laravel - 如何运行 php artisan 优化 :clear on laravel dockerized app via kubernetes