PHP COUNT并跳过其他所有记录

时间:2013-08-15 22:42:55

标签: php mysql syntax

我之前已经提出了类似的问题,但我已将其缩小范围,并希望提出一个新问题。

以下脚本将“收件人”和“发件人”日期插入到DB记录中。我想添加每隔一周跳过的选项。以下是非常接近的,它跳过了我不希望它做的第一周。有没有办法可以使用COUNT功能,只使用Count中的ODD编号记录并插入那些?

$week_day = date('w', $curr); # 0 - 6 to access the $week array

if ($week[$week_day]) { # skip if nothings in this day

    $date = date('Y-m-d', $curr);
    $sql->query("SELECT COUNT(schedule_id) FROM $pageDB WHERE doctor_id = $doc_id AND schedule_date = '$date'");

    if (!$sql->result(0)) { # skip if this is already defined
        $date = date('Y-m-d', strtotime("+1 week", $curr));
        $sql->query("INSERT INTO $pageDB (schedule_date, time, doctor_id, location_id) VALUES ('$date', '".$week[$week_day]."', $doc_id, '".$location[$week_day]."')");

    }
}

2 个答案:

答案 0 :(得分:0)

您可以添加行号,然后使用MOD(=> pos%2)来获取奇数行或偶数行。

这样的事情:

SELECT 
    a.* 
FROM 
    (
        SELECT  
            @row := @row + 1 AS pos, 
            t.* 
        FROM 
            your-TABLE t, 
            (SELECT @row := 0) b
    ) a 
WHERE 
    pos % 2 = 0

答案 1 :(得分:0)

您可以使用计数器并使用modulus- % - if($j%2 != 0)

检查它是否为偶数/奇数
$week_day = date('w', $curr); # 0 - 6 to access the $week array

$j = 1; // counter

if ($week[$week_day]) { # skip if nothings in this day

    $date = date('Y-m-d', $curr);
    $sql->query("SELECT COUNT(schedule_id) FROM $pageDB WHERE doctor_id = $doc_id AND schedule_date = '$date'");

    if ($j%2 != 0) {
        $date = date('Y-m-d', strtotime("+1 week", $curr));
        $sql->query("INSERT INTO $pageDB (schedule_date, time, doctor_id, location_id) VALUES ('$date', '".$week[$week_day]."', $doc_id, '".$location[$week_day]."')");
         $j++; // increase the counter
    }
}