簡體   English   中英

mysql表的最佳更新查詢

[英]Best update query for mysql table

我有一個文件托管站點,在這里為用戶進行每次唯一下載都提供了一個點。

我的桌子樣本
樣品表

這些積分可以由用戶兌換。 因此,例如,如果用戶要贖回100分,那么最好的查詢是減少每行可用的分數,直到減少100分。

謝謝。

您應該為此創建兩個表:

Table files
- id
- name
- size

Table points
- id
- file_id
(- user)
- points

插入一個新文件:

INSERT INTO files (name, size) VALUES ('kat92a.jpg', 105544); // New file with ID 1

現在,您可以為文件指定正負值:

INSERT INTO points (file_id, points) VALUES (1, 100); //Positive points
INSERT INTO points (file_id, points) VALUES (1, -10); //Negative points

您可以選擇總點數:

SELECT 
    files.name, 
    files.size, 
    (SELECT sum(points) FROM points WHERE file_id = 1) AS points 
FROM files
WHERE id = 1 

好吧,那么,這就是我要做的SQL愚蠢的方式。 希望SQL專家會提供更好的解決方案。 注意:這是純偽代碼; 以此為基礎編寫自己的代碼-開箱即用。

$total_to_deduct = 100;

// Each time, get the row with the highest points
$top_points_query = "SELECT id, points FROM my_table ORDER BY points DESC LIMIT 1;"

do {
  $result = do_query($top_points_query);

  if($result) {
    // I'm assuming you don't want to deduct more points from a row than it has
    $num_to_deduct = min($result['points'], $total_to_deduct);

    // Now deduct the points from the row we got earlier
    $update_query = "UPDATE my_table SET points = points - $num_to_deduct
                     WHERE id = $result['id']";

    if(do_query($update_query)) {
      $total_to_deduct -= $num_to_deduct;
    }
  }
} while($total_to_deduct > 0); // If we still have points to deduct, do it again

似乎您只需要一個簡單的update語句,就可以更新該行,如果行超過100,則不更新它。

update table set points = if( (points+<VALUE>) <= 100,points+<VALUE>,points) where id = <FILE ID>  

這將檢查點數是否大於100,如果大於100,則update語句將不返回任何結果。 如果該值小於100,則它將更新表並向您返回已更新的行數。

只需在用戶表中添加一列即可兌換的積分。 這對您來說是可行的解決方案嗎?

這是一個純SQL解決方案,但我警告您(a)這未經測試,並且(b)這只是一個概念。

DECLARE curs CURSOR FOR
    SELECT
        id,
        points,
    FROM
        points
    WHERE
        points > 0;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET remPoints = 0;
OPEN curs;

SET remPoints = 100; /* modify this value, probably in your app */

REPEAT
    FETCH curs INTO cId, cPoints;

    IF remPoints >= cPoints THEN
        UPDATE points SET points = 0 WHERE id = cId;
    ELSE
        UPDATE points SET points = points - remPoints WHERE id = cId;
    END IF;
    SET remPoints = remPoints - cPoints;
UNTIL remPoints <= 0;

CLOSE curs;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM