我已经创建了手机游戏,我将得分数据(在这种情况下为矿物)存储在sql表中。现在,我想通过从两天前的分数中减去昨天的分数来创建每日分数图表。我发现我可以用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";
我收到此错误:SQL错误:“您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取正确的语法,以在'EXCEPT SELECT玩家编号,玩家名称,矿物,daydate FROM Dailyscore附近使用da'在第3行的位置”
答案 0 :(得分:1)
不需要像EXCEPT或MINUS这样的集合运算符。只需将两天的分数相加即可计算出每日分数的差异:
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;
您可以使用此SQL并将其放在您的PHP代码中。日期应替换为存储在PHP变量中的值。
答案 1 :(得分:0)
MySQL不支持EXCEPT
。我认为您有用:
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;
注意:您不应该通过修饰字符串来传递参数。您应该学习使用?
之类的占位符正确地传递参数。