如何减去从表中选择的两个值

时间:2015-02-07 02:19:04

标签: mysql sql

我有一个MySQL表,如下所示:

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'),

我有两个问题:

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';

现在我想减去这两个查询以获得charIdexp.from.first.query - exp.from.second.query

以下是sqlfiddle.com的示例。

3 个答案:

答案 0 :(得分:0)

您需要加入两个查询然后进行数学

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 

SqlFiddle Demo

答案 1 :(得分:0)

使用自我加入。 WHERE子句将表的每个子集限制为特定时间,ON子句链接相应的行。

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'

DEMO

答案 2 :(得分:0)

在您的示例数据中,两个组中相同ID的exp值相同。所以从另一个中减去一个只会导致零。

但是,假设您的实际数据具有不同的值,这里有一种方法可以在不加入表格的情况下执行操作。

SELECT  CharId,
        Sum( case LadderTime
             when :SecondDate then exp
             else -exp end )as SumExp
FROM    LadderStandard
where   LadderTime in( :FirstDate, :SecondDate )
group by CharID;

正如所料,此 SQL Fiddle 显示除CharID = 10291之外的所有零,其中第二组中有一个条目,但第一组中没有条目。在这种情况下,计算结果为0 - exp.from.second.query,这只是exp值的负数。