MySQL中的查询加速

时间:2018-08-09 02:34:54

标签: php mysql

此代码收集并带来100万条记录中的结果。 此过程需要很多时间才能显示出来。 我怎样才能更快呢?

$urunler       = $db->get_results("SELECT urunid,urunadi FROM sf_urun01 WHERE sil!=2");
foreach ($urunler as $urun ){


$a   = $db->get_var("SELECT SUM(tonaj) FROM sf_urun10 WHERE urunid='$urun->urunid' AND (durumu='GIRIS' OR durumu='HATALI') AND cariid > 5 AND  sil !=2");
$b   = $db->get_var("SELECT SUM(tonaj) FROM sf_urun10 WHERE urunid='$urun->urunid'AND (durumu='GIRIS' OR durumu='HATALI') AND cariid < 5 AND istifyeri!='FASON'  AND   sil !=2");
$c   = $db->get_var("SELECT SUM(tonaj) FROM sf_urun10 WHERE urunid='$urun->urunid' AND durumu='HATALI' AND cariid < 5 AND  sil !=2");

$d   = $db->get_var("SELECT SUM(tonaj) FROM sf_urun10 WHERE urunid='$urun->urunid' AND istifyeri='FASON' AND (durumu='GIRIS' OR durumu='HATALI') AND cariid > 5 AND  sil !=2");


/*
Using Datatable 
*/

}

1 个答案:

答案 0 :(得分:2)

我认为您可以将所有这些查询合并为一个查询,该查询应该更快:

SELECT urunid,
    SUM(
        CASE WHEN (durumu='GIRIS' OR durumu='HATALI') AND cariid > 5 THEN tonaj
        ELSE 0 END) 
    AS a,
    SUM(
        CASE WHEN (durumu='GIRIS' OR durumu='HATALI') AND cariid < 5 AND istifyeri!='FASON' THEN tonaj
        ELSE 0 END) 
    AS b,
    SUM(
        CASE WHEN durumu='HATALI' AND cariid < 5 THEN tonaj
        ELSE 0 END)
    AS c,
    SUM(
        CASE WHEN istifyeri='FASON' AND (durumu='GIRIS' OR durumu='HATALI') AND cariid > 5 THEN tonaj
        ELSE 0 END)
    AS d
FROM sf_urun10
WHERE sil !=2
GROUP BY urunid

这将给出一个表格形式

urunid  a   b   c   d
1       56  252 15  76
etc.