I have a MySQL table, like this:
CREATE TABLE IF NOT EXISTS `ladderStandard` (
`charId` mediumint(8) unsigned NOT NULL,
`poeRank` smallint(5) unsigned NOT NULL,
`lvl` tinyint(3) unsigned NOT NULL,
`exp` int(10) unsigned NOT NULL,
`ladderTime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `ladderStandard` (`charId`, `poeRank`, `lvl`, `exp`, `ladderTime`) VALUES
(10000, 10000, 91, 2108226870, '2015-02-06 23:37:11'),
(10001, 10001, 91, 2108221545, '2015-02-06 23:37:11'),
(10002, 10002, 91, 2108219833, '2015-02-06 23:37:11'),
(10003, 10003, 91, 2108192924, '2015-02-06 23:37:11'),
(10004, 10004, 91, 2108154502, '2015-02-06 23:37:11'),
(10005, 10005, 91, 2108153763, '2015-02-06 23:37:11'),
(10000, 9998, 91, 2108226870, '2015-02-06 23:58:21'),
(10001, 9999, 91, 2108221545, '2015-02-06 23:58:21'),
(10002, 10000, 91, 2108219833, '2015-02-06 23:58:21'),
(10003, 10001, 91, 2108192924, '2015-02-06 23:58:21'),
(10004, 10002, 91, 2108154502, '2015-02-06 23:58:21'),
(10005, 10003, 91, 2108153763, '2015-02-06 23:58:21'),
I have two queries:
SELECT charId, exp FROM ladderStandard WHERE ladderTime = '2015-02-06 23:37:11';
SELECT charId, exp FROM ladderStandard WHERE ladderTime = '2015-02-06 23:58:21';
Now I want subtract these two queries to get charId
and exp.from.first.query
- exp.from.second.query
Here is an example on sqlfiddle.com .
You need to join both the queries then do the math
SELECT a.charid,
a.exp - b.exp
FROM (SELECT charId,
exp
FROM ladderStandard
WHERE ladderTime = '2015-02-06 23:37:11') a
JOIN (SELECT charId,
exp
FROM ladderStandard
WHERE ladderTime = '2015-02-06 23:58:21') b
ON a.charid = b.charid
Use a self-JOIN. The WHERE
clause will restrict each subset of the table to the specific time, and the ON
clause links the corresponding rows.
SELECT a.charid, a.exp - b.exp AS diff
FROM ladderStandard AS a
JOIN ladderStandard AS b ON a.charid = b.charid
WHERE a.ladderTime = '2015-02-06 23:37:11'
AND b.ladderTime = '2015-02-06 23:58:21'
In your sample data, the exp
values are the same for the same ID in both groups. So subtracting one from the other will just result in zero.
However, on the assumption that your actual data has different values, here is a way to perform the operation without joining the table.
SELECT CharId,
Sum( case LadderTime
when :SecondDate then exp
else -exp end )as SumExp
FROM LadderStandard
where LadderTime in( :FirstDate, :SecondDate )
group by CharID;
As expected, this SQL Fiddle shows all zeros except for CharID
= 10291, which has an entry in the second group but not the first. In that case, the calculation is 0 - exp.from.second.query
which is just the negative of the exp
value.
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.