背景:
业务逻辑:
BEGIN;
创建临时表
CREATE TEMPORARY TABLE tmp (
id BIGINT PRIMARY KEY
);
插入数据到临时表
INSERT INTO tmp (id)
SELECT id
FROM t1
INNER JOIN t2
ON t1.id = t2.pid
AND t1.a = 3305078257
AND t1.b = 2
AND t1.c != -1
AND t1.a = 3305078257
AND t2.a != -1;
数临时表中的数据
SET @c1 = (SELECT COUNT(1) FROM tmp);
根据临时表数据的返回值确定执行的 SQL
SET @query =
CASE
WHEN @c1 < 5000 THEN
'SELECT COUNT(1) FROM tmp (执行特别慢的部分)
INNER JOIN t3
ON tmp.id = t3.gid
AND status != -1
AND a_status = -3;'
ELSE
'SELECT COUNT(1) FROM tmp
INNER JOIN t3
ON tmp.id = t3.gid
AND t3.status != -1
AND t3.a_status = -3
AND t3.uid = 3364766306;'
END;
执行相应 SQL
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DROP TEMPORARY TABLE IF EXISTS tmp;
COMMIT;
- t3 表有百亿的一个规模
- 数据库版本 5.4.1
问题:
我们发现不带 where 条件执行特别慢,于是我们改写了下 SQL,加上了 where ,有效果
SELECT COUNT(1) FROM tmp
INNER JOIN t3
ON tmp.id = t3.gid
where
status != -1
AND a_status = -3;
但是增加了一个条件就一直无法出数据,我们尝试过直接执行 SELECT COUNT(1) FROM tmp INNER JOIN t3 ON tmp.id = t3.gid 结果很快 join 出来的结果大约 4000 条,只要一加上后面 3 个 where 条件就无法出结果,我理解临时表和 t3 表 inner join 的结果大约有 4000 ,后面的结果应该只回去扫描 4000 条,但是我感觉还是去扫描了 t3 表,因为这个 SQL 执行时间很长,一直没有拿到执行计划,烦请各位帮忙看下,多谢
SELECT COUNT(1) FROM tmp
INNER JOIN t3
ON tmp.id = t3.gid
where
status != -1
AND a_status = -3
AND ma_status in (1,-7)