How can I optimize such a sql??

SELECT 
    * 
FROM `t_test` 
WHERE ( `pid` IN ( SELECT id FROM `t_test` WHERE `pid` = "1" AND type = 1 ) AND type = 2 ) OR ( `pid` = "1" AND type = 2 )

the structure of the data table is as follows:

clipboard.png

?

:
INSERT INTO agent.t_test (id, pid, type) VALUES ("1", "0", "0");
INSERT INTO agent.t_test (id, pid, type) VALUES ("2", "1", "1");
INSERT INTO agent.t_test (id, pid, type) VALUES ("3", "2", "2");
INSERT INTO agent.t_test (id, pid, type) VALUES ("4", "1", "2");
INSERT INTO agent.t_test (id, pid, type) VALUES ("5", "1", "1");
INSERT INTO agent.t_test (id, pid, type) VALUES ("6", "5", "2");
INSERT INTO agent.t_test (id, pid, type) VALUES ("7", "2", "2");
INSERT INTO agent.t_test (id, pid, type) VALUES ("8", "5", "1");

CREATE TABLE t_test (
id int(11) NOT NULL AUTO_INCREMENT,
pid int(11) NOT NULL,
type tinyint(4) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;

:

clipboard.png

Dec.24,2021

WHERE ( `pid` IN ( SELECT id FROM `t_test` WHERE `pid` = '1') AND type = 2 )

select a.* from t_test a join 
(select '1' id union    
SELECT id FROM `t_test` WHERE `pid` = '1' AND type = 1) b
on a.pid=b.id and a.type=2;

if the amount of data is large, pid needs to add an index

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b36985-2c01c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b36985-2c01c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?