MySQL - 从另一个结果中扣除一个查询的结果

时间:2015-01-26 09:50:29

标签: mysql

我正在运行两个查询。

他们是:

首次查询

SELECT SUM(dbase1.transaction.amount) AS total, dbase1.player.name 
FROM dbase1.transaction
JOIN dev2.player ON dbase1.transaction.player_id = dbase1.player.player_id
WHERE (dbase1.transaction.type !=1)
AND (dbase1.transaction.type !=3) 
GROUP BY dbase1.transaction.player_id 
ORDER BY name ;

和第二个查询

SELECT dbase2.transaction.amount
, dbase2.transaction.player_id
, dbase2.player.name 
FROM dbase2.transaction
JOIN dbase2.player ON dbase2.transaction.player_id = dbase2.player.player_id
WHERE dbase2.transaction.provider ='providerx';

在第一个结果集中,我得到一个金额和一个名字,在第二个结果集中,我得到一个金额,一个名字和一个ID。

我想要的是从名字匹配的第一组第二组结果中扣除金额。

基本上我的最终结果是:

amount from set1 - amount from set2, name, id

我希望这是有道理的,任何建议都会受到赞赏

由于

2 个答案:

答案 0 :(得分:0)

加入他们。

select a.total - b.amount from (
    select sum(dbase1.transaction.amount)
    as total, dbase1.player.name from dbase1.transaction
    JOIN dev2.player on
    dbase1.transaction.player_id = dbase1.player.player_id
    where
    (dbase1.transaction.type !=1)
    and
    (dbase1.transaction.type !=3) group by dbase1.transaction.player_id
) query_a a
INNER JOIN 
(
    select dbase2.transaction.amount, dbase2.transaction.player_id, dbase2.player.name from dbase2.transaction
    JOIN dbase2.player ON
    dbase2.transaction.player_id = dbase2.player.player_id
    where dbase2.transaction.provider ='providerx'
) query_b b on a.name = b.name

答案 1 :(得分:0)

您可以将两个查询用作派生表并执行此操作:

select 
    q1.total - q2.amount, q2.name, q2.player_id 
from (
    select 
       sum(dbase1.transaction.amount) as total, 
       dbase1.player.name 
    from dbase1.transaction
    join dev2.player on dbase1.transaction.player_id = dbase1.player.player_id
    where 
       (dbase1.transaction.type !=1)
       and
       (dbase1.transaction.type !=3) 
    group by dbase1.transaction.player_id
    ) q1
join (
    select 
       dbase2.transaction.amount, 
       dbase2.transaction.player_id, 
       dbase2.player.name 
    from dbase2.transaction
    join dbase2.player on dbase2.transaction.player_id = dbase2.player.player_id
    where dbase2.transaction.provider ='providerx'
    ) q2 on q1.name = q2.name