Image enter image description here enter image description here
I am trying to figuring out a way to get rid of using temporary by creating index.
My SQL code:
EXPLAIN SELECT SQL_NO_CACHE COUNT(*) AS NUMBER, b.deptName,b.id
FROM t_emp AS a
LEFT JOIN t_dept AS b
ON b.id = a.deptid
WHERE a.age > 40 AND a.empno <> 0
GROUP BY a.deptid
HAVING NUMBER >= 2
Here is the creating of the table:
CREATE TABLE t_dept(
id INT(11) NOT NULL AUTO_INCREMENT,
deptName VARCHAR(30) DEFAULT NULL,
address VARCHAR(40) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE t_emp(
id INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) DEFAULT NULL,
age INT(3) DEFAULT NULL,
deptId INT(11) DEFAULT NULL,
empno INT NOT NULL,
PRIMARY KEY (id),
KEY idx_dept_id (deptId)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO t_dept(deptName,address) VALUES
('HR','NY'),
('IT','CA'),
('DEV', 'SC');
INSERT INTO t_emp(NAME,age,deptId,empno) VALUES
('JACK',90,1,100001),
('DAVID',50,1,100002),
('MIKE',24,1,100003),
('JOE', 90,1, 100001);