简体   繁体   English

如何从一个SQL表中的数据减去PHP中的另一个SQL表?

[英]How to subtract data from one sql table from another in php?

I have created mobile game, I store score data(minerals in this case) in sql table. 我已经创建了手机游戏,我将得分数据(在这种情况下为矿物)存储在sql表中。 Now I want to create daily score chart by subtracting yesterday scores from scores two days old. 现在,我想通过从两天前的分数中减去昨天的分数来创建每日分数图表。 I have found that I can do it with EXCEPT but nothing I try works. 我发现我可以用EXCEPT做到这一点,但是我没有尝试。

    $sql = "SELECT playerid, playername, minerals, daydate
    FROM dailyscore WHERE daydate = '".$yesterday."'
    EXCEPT
    SELECT playerid, playername, minerals, daydate
    FROM dailyscore WHERE daydate = '".$twodays."'
    ORDER BY minerals DESC";

I get this error: SQL Error: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EXCEPT SELECT playerid, playername, minerals, daydate FROM dailyscore WHERE da' at line 3" 我收到以下错误消息:SQL错误:“您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取正确的语法,以在'EXCEPT SELECT玩家ID,玩家名称,矿物,daydate FROM Dailyscore WHERE da'附近使用在第3行

There is no need for set operators like EXCEPT or MINUS. 不需要像EXCEPT或MINUS这样的集合运算符。 Just calculate the difference of the daily scores by joining the scores of the two days: 只需将两天的分数相加即可计算出每日分数的差额:

SELECT playerid, playername, minerals
FROM (
    SELECT ds_yesterday.playerid,
        ds_yesterday.playername,
        CASE
            WHEN ds_twodays.minerals IS NULL
            THEN ds_yesterday.minerals
            ELSE ds_yesterday.minerals - ds_twodays.minerals
        END minerals
    FROM dailyscore as ds_yesterday
    LEFT JOIN dailyscore as ds_twodays ON 
        ds_twodays.playerid = ds_yesterday.playerid
        AND ds_twodays.daydate = '2018-08-07'
    WHERE ds_yesterday.daydate = '2018-08-08'
) scoredifference
ORDER BY minerals DESC;

You can use this SQL and place it in your PHP code. 您可以使用此SQL并将其放在您的PHP代码中。 Dates should be replaced by the values stored in the PHP variables. 日期应替换为存储在PHP变量中的值。

MySQL doesn't support EXCEPT . MySQL不支持EXCEPT I think you an use: 我认为您有用途:

SELECT ds.playerid, ds.playername, ds.minerals, ds.daydate
FROM dailyscore ds
WHERE daydate = '".$yesterday."' AND
      NOT EXISTS (SELECT 1
                  FROM dailyscore
                  WHERE ds2.playerid = ds.playerid AND
                        ds2.minerals = ds.minerals AND
                        ds2.daydate = '".$twodays."'
                 )
ORDER BY ds.minerals DESC;

Note: You shouldn't be passing in parameters by munging strings. 注意:您不应该通过修饰字符串来传递参数。 You should learn to pass in parameters correctly, using placeholders such as ? 您应该学习使用诸如?占位符正确地传递参数? .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM