I have created mobile game, I store score data(minerals in this case) in sql table. 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.
$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"
There is no need for set operators like EXCEPT or 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. Dates should be replaced by the values stored in the PHP variables.
MySQL doesn't support 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 ?
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.