2013-08-23 47 views
1

我使用PHP和MySQL數據庫INSERT MySQL的記錄,如果條件得到滿足

以便讓它能夠插入你的分數,然後告訴你你的位置,我得到了它創造高分表的遊戲,但以防止我希望它檢查以下同一個人垃圾郵件板,

if score from your IP exists and score > your_current_highscore 
UPDATE score 

這是很容易的,是什麼使得它很難是而不是「得分」有2個變量,「TIME」(如何長時間完成)和「PERCENT」(他們完成了多少遊戲)。

我不知道如何構造SQL語句,我是否需要

if time OR percent > current 

;或

if time AND percent > current 

時間將是主要的排序,以百分之二

誰能uncomplicate這給我嗎?

+0

所以更快地獲得更多的遊戲會導致更好的排名,並因此更新現有記錄?如果IP地址不匹配,查詢是否需要插入? –

+0

是的,這是正確的。我可以處理插入,如果它不存在,它只是更新的一部分,我不能讓我的頭因爲兩個變量 – user961882

+0

如果玩家獲得更多的遊戲,但需要更長時間? –

回答

0

此查詢將更新記錄,如果

  1. 新的時間更好,百分比更好或相等,或
  2. 新時間是相同的,但完成的百分比更好:

    UPDATE leaderboards 
    SET time=[player new time], 
        percent=[player new percent] 
    WHERE ip=[player IP] 
        AND (
         /*new time is better than old time AND new percent is better than or equal to old percent*/ 
         time > [player new time] 
          AND percent <=[player new percent] /*maybe you don't want this condition, see next proposal*/ 
    
         /*OR new time is equal to old time AND new percent is better than old percent */ 
         OR (
         time =[player new time] 
          AND percent < [player new percent]) 
        ) 
    

另外,如果

  1. 新的時間(無論變化的百分比)更好的這個查詢將更新記錄,或
  2. 新的時間是相同的,但百分比完成較好:

    UPDATE leaderboards 
    SET time=[player new time], 
        percent=[player new percent] 
    WHERE ip=[player IP] 
        AND (
         /*new time is better than old time, regardless of change in percent*/ 
         time > [player new time] 
    
         /*OR new time is equal to old time AND new percent is better than old percent */ 
         OR (
         time =[player new time] 
          AND percent < [player new percent]) 
        ) 
    
+0

我正在處理我自己的代碼來回答這個問題,但是你的工作更加簡潔,謝謝。 – user961882

+0

如果您想要更復雜一點,可以添加一些基於範圍的邏輯來改善效果,例如:'time * 1.05> [player new time] AND percent * 1.10 <[player new percent]',它會更新記錄時間是否在上一次的5%以內(即使更差),但百分比要好10%。 –

1

嘗試(排序爲表名的元語言):

UPDATE score_table 
SET score = new_score 
WHERE score > your_current_highscore AND 
     score in (SELECT score 
       FROM table_with_ips 
       WHERE ip = your_ip) AND 
     user_id = your_user_id 

如果score > your_current_highscore是假的,那麼就沒有任何條目將被更新。

既然你有兩個參數(時間和百分比)和第一個是占主導地位的,你可以查成績是這樣的:

--- score > your_current_hightscore 
+++ time > your_current_time OR 
+++ (time = your_current_time AND percentage > your_current_percentage) 
+0

問題在於它不是'分數',而是2個變量 - '百分比'和'時間'。 '時間'是主要的 – user961882

相關問題