在foreach循环中使用sql查询进行foreach循环

时间:2015-08-27 21:32:20

标签: php mysql

我需要这个循环的帮助......我有地址数据表:

class SelfRefrencingQuerySet(models.query.QuerySet):
    pass

class SelfRefrencingManager(BaseManager):

    def get_queryset(self):
        return SelfRefrencingQuerySet(self.model, self._db).filter(
            deleted__isnull=True)

class SelfRefrencingBaseModel(models.Model):

    children = models.ManyToManyField('self', blank=True, symmetrical=False,
        related_name='parents')

    # Manager
    objects = SelfRefrencingManager()
    objects_all = models.Manager()     # So you still have acccess to the
                                       # default Manager

和mysql查询:

konto_odbiorcy   nazwa     miasto     zip_code    ulica
6                 firm 1    Warsaw     02-174      street 1
23                firm 2    Krakow     05-400      street 2
435               firm 3    Warsaw      26-143      street 3
534               firm 4    Kielce     14-171      street 4
643               firm 5    Krakow     08-199      street 5
...something about 5000 entries

结果:

$sql = 'SELECT
    konto_odbiorcy,nazwa,miasto,zip_code,ulica
FROM
    klienci_ax_all
WHERE
    sales_group IN ("IN","KD","TK","SG","TD")
ORDER BY
    miasto
ASC';

$res = mysql_query ($sql, $link ) or die ('request "Could not execute SQL query" '.$sql);

$cities = array();

while ($row = mysql_fetch_array($res)){
    $cities[$row['miasto']][] = $row;
}

foreach ($cities as $miasto => $_cities){
    echo $miasto;

    foreach ($_cities as $data){
        $sql1 = "SELECT date 
                 FROM 3ce_event
                 WHERE number=".$data['konto_odbiorcy']."
                 AND date <= CURDATE())
                 ORDER BY date
                 DESC LIMIT 0,1";
        $sql_result1 = mysql_query ($sql1, $link ) or die ('request "Could not execute SQL query" '.$sql1);

        $sql2 = "SELECT date FROM 3ce_event
                 WHERE number=".$data['konto_odbiorcy']."
                 AND date >= CURDATE()) ORDER BY date ASC LIMIT 0,1";
        $sql_result2 = mysql_query ($sql2, $link ) or die ('request "Could not execute SQL query" '.$sql2);


        while ($row1 = mysql_fetch_assoc($sql_result1)) {
            if($row1["date"] <> $obecna_data) {
                $data_ostatniej_wizyty = $row1["date"];
              }
        }

        while ($row2 = mysql_fetch_assoc($sql_result2)) {
            if( $row2["date"] == $obecna_data) {
                $data_nastepnej_wizyty = 'dzis';
            } else {
                $data_nastepnej_wizyty = $row2["date"];
            }
        }
    }
}

现在它工作但很棒,当我首先搜索整个表并首先搜索“城市”时,再搜索位于特定城市的公司(“nazwa”)。

我的问题是如何提高这项工作的速度?

修改

我将第二个mysql查询粘贴到第二个foreach循环中。

1 个答案:

答案 0 :(得分:0)

不要在循环中执行这些SQL查询。将它们组合在一个SQL语句中:

$sql = 'SELECT a.konto_odbiorcy, a.nazwa, a.miasto, a.zip_code, a.ulica
, max(e1.date) as date_le_curdate
, min(e2.date) as date_ge_curdate
FROM klienci_ax_all as a
LEFT JOIN 3ce_event as e1 ON (a.konto_odbiorcy=e1.number AND e1.date <= CURDATE())
LEFT JOIN 3ce_event as e2 ON (a.konto_odbiorcy=e2.number AND e2.date >= CURDATE())
WHERE a.sales_group IN ("IN","KD","TK","SG","TD")
GROUP BY a.konto_odbiorcy
ORDER BY a.miasto ASC';

表konto_odbiorcy应该在sales_group上有一个索引 - 可能与miasto结合(假设konto_odbiorcy是主键或至少是一个唯一键)。 3ce_event应该有一个数字索引。但微调取决于您的表包含哪些数据。