MySQL计算w / php试图优化效率和非冗余

时间:2012-02-26 07:18:56

标签: php mysql count

我的查询工作正常。但我试图找出最佳的优化方法,而不是重复我的$ sqlRecCount和$ records_count(并想知道是否可能不需要复制GET)。这就是我现在所拥有的:

if ((int)$_GET['products_id'] === 13) {
    $sqlRecCount = "select count(*) as recTotal from table_sql_1";
    $recCnt = $db->Execute($sqlRecCount);
    $records_count = $recCnt->fields['recTotal'];
}
elseif ((int)$_GET['products_id'] === 2) { 
    $sqlRecCount = "select count(*) as recTotal from table_sql_2";
$recCnt = $db->Execute($sqlRecCount);
    $records_count = $recCnt->fields['recTotal'];
} else {
    $records_count = "Updating...";
}

2 个答案:

答案 0 :(得分:0)

$id = intval($_GET['products_id']);

if ($id == 13 || $id == 2) {
    $sqlRecCount = "select count(*) as recTotal from table_sql_" . 
                                                       ($id==13?'1':'2');
    $recCnt = $db->Execute($sqlRecCount);
    $records_count = $recCnt->fields['recTotal'];
} else {
    $records_count = "Updating...";
}

ps:如果你有一组没有与product_id直接对应的表,你可以重写代码段

$id = intval($_GET['products_id']); // casting to int is not required here
$tables = array('13'=>'1', '2'=>'2', and so on);  

if (isset($tables[$id])) {
    $sqlRecCount = "select count(*) as recTotal from table_sql_" . $tables[$id];
    $recCnt = $db->Execute($sqlRecCount);
    $records_count = $recCnt->fields['recTotal'];
} else {
    $records_count = "Updating...";
}

ps: @downvoter - 任何评论?

答案 1 :(得分:0)

正确的方式显然是

if ($id = (int)$_GET['products_id']) {
    $sql = "SELECT count(*) as total FROM table_sql WHERE products_id=$id";
    $res = $db->Execute($sql);
    $records_count = $res->fields['total'];
}

或根据您的db API语法

的类似内容