我仍然发现如何在mysql中查询查询快速数据的方法,我尝试做一个功能,但搜索数据仍然很慢,这里是我的原始查询
SELECT B.totResi as TotResi,C.totResi as TotDeliv,D.totResi as TotPending,E.totResi as TotRetur
FROM Table1 A
LEFT JOIN (SELECT count(ID) as totResi,Id_Table1 from Table2 group by Id_Table1) B ON A.ID=B.Id_Table1
LEFT JOIN (SELECT count(ID) as totResi,Id_Table1 from Table2 where status=0 group by Id_Table1) C ON A.ID=C.Id_Table1
LEFT JOIN (SELECT count(ID) as totResi,Id_Table1 from Table2 where status=1 group by Id_Table1) D ON A.ID=D.Id_Table1
LEFT JOIN (SELECT count(ID) as totResi,Id_Table1 from Table2 where status=2 group by Id_Table1) E ON A.ID=E.Id_Table1
WHERE A.ID=22340 order by A.ID desc
而且我正在尝试做一个功能,这是我的功能之一
DELIMITER $$
CREATE FUNCTION tot_resi (ID int) RETURNS INT DETERMINISTIC
BEGIN
DECLARE total INT;
SELECT count(a.ID) as totResi into total from Table2 a where a.Id_Table1=ID;
RETURN total;
END$$
DELIMITER ;
并且我这样称呼功能
SELECT tot_resi(22340) as TotResi,tot_resi_deliv(22340) as TotDeliv,tot_resi_pending(22340) as TotPending,tot_resi_retur(22340) as TotRetur
我已经在Id_Table1
的Table2
处添加了索引,但是它仍然发现数据非常慢,您对加快搜索数据有任何建议吗?
似乎您需要简单
SELECT COUNT(t1.id),
SUM(t2.status=0),
SUM(t2.status=1),
SUM(t2.status=2)
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.Id_Table1
WHERE t1.id=22340