Home About Me

SQL Patterns for Rank Gaps, Neighboring Posts, and Bulk Updates

SQL query patterns illustration

Some features look simple from the interface but become a small SQL puzzle behind it. The cases below are the kind that tend to come back: finding a contestant's rank and the gap to the person above, retrieving the previous/next article even when IDs are missing, updating many rows with different values in one statement, and replacing strings in bulk.

Ranking a contestant and finding the gap

One way is to count how many contestants are ahead and add one. This gives the rank, but it does not directly return the previous contestant's vote total. The fallback in the example subtracts the current contestant's total from the value returned by the query; that value represents the gap to the first-place contestant.

$temp = DB::fetch_first("SELECT distinct total+jewel_vote+forge_vote  ,COUNT(*)+1 AS RANK FROM " . DB::table('vote_competition') ." WHERE total+jewel_vote+forge_vote>" . $competition['all'] . " and aid={$aid} ORDER by forge_vote desc");
$rank = $temp['RANK'];
// Cannot directly query the previous contestant's vote total
if ($temp['total+jewel_vote+forge_vote']) {
    // What is queried here is the vote difference from the first-place contestant
    $up = $temp['total+jewel_vote+forge_vote']-$competition['all'];
}

Another approach sorts the rows and assigns a row number with a user variable. It scans the ordered list, records the rank when it reaches the target cid, and keeps the previous row's vote total so the gap can be calculated by subtracting the current contestant's total.

$temp = DB::fetch_all("SELECT a.cid,a.total,a.forge_vote,a.jewel_vote,(@rowNum:=@rowNum+1) AS rank FROM pre_vote_competition AS a, (SELECT (@rowNum :=0) ) b WHERE aid={$aid} ORDER BY (a.total+a.forge_vote+a.jewel_vote) DESC ");
foreach ($temp as $key => $value) {
    if ($value['cid'] == $cid) {
        // Current contestant's rank
        $rank = $value['rank'];
        if ($up) {
            $up = $up - ($value['total'] +  $value['forge_vote'] + $value['jewel_vote']);
        }
        break;
    }
    // Vote difference from the contestant above
    $up = $value['total'] +  $value['forge_vote'] + $value['jewel_vote'];
}

Previous and next article, with gaps in IDs

For previous/next navigation, IDs are often not contiguous. A direct id - 1 or id + 1 lookup fails when rows have been deleted. The query below uses SIGN(aid - {$id}) to split rows into those lower and higher than the current ID, then takes MAX for the previous one and MIN for the next one. That way missing numbers do not break navigation.

$sql = "
SELECT
    *
FROM
    " . DB::table($this->_table) . "
WHERE
    aid IN (
        SELECT
            CASE
            WHEN SIGN(aid - {$id}) > 0 THEN MIN(aid)
            WHEN SIGN(aid - {$id}) < 0 THEN MAX(aid)
            END AS aid
        FROM
            pre_exe_article
        WHERE
            aid <> {$id}
        GROUP BY
            SIGN(aid - {$id})
        ORDER BY
            SIGN(aid - {$id})
    )
ORDER BY
    aid ASC";
return DB::fetch_all($sql);

Updating many rows with different values

A single row update is straightforward:

UPDATE mytable SET myfield = 'value' WHERE id = '1';

When the same value applies to several rows, the WHERE clause can simply use IN:

UPDATE mytable SET myfield = 'value' WHERE id in (1,2,3);

But when each row needs a different value, a common first instinct is to loop and run one update per row:

foreach ($display_order as $id => $ordinal) {
    $sql = "UPDATE categories SET display_order = $ordinal WHERE id = $id";
    mysql_query($sql);
}

That performs one update per record. It is poor for performance and can easily create blocking. MySQL does not provide a direct syntax for bulk-updating different values, but CASE can do the job in a single statement:

UPDATE mytable SET
    myfield = CASE id
        WHEN 1 THEN '3'
        WHEN 2 THEN '4'
        WHEN 3 THEN '5'
    END
WHERE id IN (1,2,3)

The statement means: set display_order to 3 when id=1, to 4 when id=2, and to 5 when id=3. The conditions are written together in the CASE expression. The WHERE clause does not change the logic, but it limits the statement to the rows that actually need updating and improves execution efficiency. Here it ensures only the three target rows are touched.

Multiple fields can be updated the same way:

UPDATE categories SET
    display_order = CASE id
        WHEN 1 THEN 3
        WHEN 2 THEN 4
        WHEN 3 THEN 5
    END,
    title = CASE id
        WHEN 1 THEN 'New Title 1'
        WHEN 2 THEN 'New Title 2'
        WHEN 3 THEN 'New Title 3'
    END
WHERE id IN (1,2,3)

The PHP functions below wrap this pattern and generate the SQL from the data, table, field, and extra conditions.

/**
 * Batch update function
 * @param $data array Data to update, as a two-dimensional array
 * @param array $params array Conditions with the same value, as a key-value one-dimensional array
 * @param string $table array Table
 * @param string $field string Condition for different values, defaults to id
 * @return bool|string
 */
function batchUpdate($data, $field, $table ,$params = [])
{
   if (!is_array($data) || !$field || !$table || !is_array($params)) {
      return false;
   }

    $updates = parseUpdate($data, $field);
    $where = parseParams($params);

    // Get all values of the $field column, add single quotes around each value, and store them in the $fields array
    // array_column() requires PHP 5.5.0+; if using an older version, implement it yourself.
    // Reference: http://php.net/manual/zh/function.array-column.php#118831
    $fields = array_column($data, $field);
    $fields = implode(',', array_map(function($value) {
        return "'".$value."'";
    }, $fields));

    $sql = sprintf("UPDATE `%s` SET %s WHERE `%s` IN (%s) %s", $table, $updates, $field, $fields, $where);

   return $sql;
}

/**
 * Convert a two-dimensional array into CASE WHEN THEN batch update conditions
 * @param $data array Two-dimensional array
 * @param $field string Column name
 * @return string SQL statement
 */
function parseUpdate($data, $field)
{
    $sql = '';
    $keys = array_keys(current($data));
    foreach ($keys as $column) {

        $sql .= sprintf("`%s` = CASE `%s` \n", $column, $field);
        foreach ($data as $line) {
            $sql .= sprintf("WHEN '%s' THEN '%s' \n", $line[$field], $line[$column]);
        }
        $sql .= "END,";
    }

    return rtrim($sql, ',');
}

/**
 * Parse WHERE conditions
 * @param $params
 * @return array|string
 */
function parseParams($params)
{
   $where = [];
   foreach ($params as $key => $value) {
      $where[] = sprintf("`%s` = '%s'", $key, $value);
   }

   return $where ? ' AND ' . implode(' AND ', $where) : '';
}

Replacing strings in bulk

A targeted REPLACE can also be done across matching rows without fetching and rewriting each record in application code:

UPDATE `emlog_blog` SET `content` = replace (`content`,'ws2.sinaimg.cn','cdn.sinaimg.cn.52ecy.cn') WHERE `content` LIKE '%ws2.sinaimg.cn%'