【问题标题】:INSERT mySQL record if conditions are met如果满足条件,则插入 mySQL 记录
【发布时间】:2013-08-23 13:33:43
【问题描述】:

我正在使用 PHP 和 MySQL 数据库为游戏创建高分表

我已经得到它,它可以插入你的分数,然后告诉你你的位置,但为了防止与同一个人向董事会发送垃圾邮件,我希望它检查以下内容,

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

这很容易,但更难的是,不是“分数”,而是 2 个变量,“时间”(完成游戏所用的时间)和“百分比”(他们完成了多少游戏)。

我不确定如何构建 SQL STATEMENT,是否需要

if time OR percent > current

或;

if time AND percent > current

TIME 将是主要的 SORT,百分比为秒

谁能帮我解决这个问题?

【问题讨论】:

  • 所以更快地完成更多游戏会带来更好的排名,从而更新现有记录?如果 IP 地址不匹配,是否需要插入查询?
  • 是的,没错。如果插入不存在,我可以处理它,它只是更新部分,由于 2 个变量,我无法理解
  • 如果玩家完成更多游戏,但需要更长时间怎么办?
  • 重点是速度跑的时间
  • 表的名称是什么?上面有哪些字段?

标签: php mysql sql insert


【解决方案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)

【讨论】:

  • 问题是它不是“分数”,而是 2 个变量——“百分比”和“时间”。 “时间”是主要的
【解决方案2】:

此查询将更新记录,如果

  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])
        )
    

【讨论】:

  • 我正在编写自己的代码来回答这个问题,但你的代码更简洁,谢谢。
  • 如果您想要更复杂一点,请添加一些基于范围的逻辑以进行改进,即:time * 1.05 &gt; [player new time] AND percent * 1.10 &lt; [player new percent],如果时间在上次的 5% 以内,则会更新记录时间(即使更糟),但在百分比上好 10%。
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-10-26
相关资源
最近更新 更多