T-sql查询问题

时间:2018-05-05 17:33:33

标签: mysql sql join

我有像这样的查询

SELECT
    a.ID,
    b.ID,
    a.Wallet,
    b.Total
FROM
    a
INNER JOIN b ON b.IID= a.ID
WHERE
    b.ID= 19
AND b.IsActive = 1

我得到了这个结果

a.ID      b.ID     Wallet      Total
1         19        1000        250
1         19        1000        500

当我运行此查询时

UPDATE a
INNER JOIN b ON b.IID= a.ID
SET a.Wallet= a.Wallet+ b.Total
WHERE
    b.ID= 19
AND b.IsActive = 1

我的b表钱包值从1000更新到1250,但真正的结果是b表钱包值从1000到1750,哪里是我的失败?

  

******EDİT******

表架构

CREATE TABLE IF NOT EXISTS `wallets` (
  `wallet_id` int(6) unsigned NOT NULL,
  `wallet` int(3) unsigned NOT NULL,
  PRIMARY KEY (`wallet_id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `wallets` (`wallet_id`, `wallet`) VALUES
  ('1', '100'),
  ('2', '100');

  CREATE TABLE IF NOT EXISTS `totals` (
  `id` int(6) unsigned NOT NULL,
   `TotalID` int(6) unsigned NOT NULL,
  `wallet_id` int(6) unsigned NOT NULL,
  `total` int(3) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `totals` (`id`, `TotalID`,`wallet_id`,`total`) VALUES
  ('1', '19','1', '250'),
 ('2', '19','1', '750');

更新查询

UPDATE wallets inner join totals on totals.wallet_id=wallets.wallet_id
SET 
wallets.wallet=wallets.wallet+totals.total
Where totals.TotalID=19

选择查询

SELECT * from wallets inner join totals on totals.wallet_id=wallets.wallet_id

4 个答案:

答案 0 :(得分:1)

UPDATE  a
SET     wallet = wallet + b_sum
FROM    a
CROSS APPLY
        (
        SELECT  SUM(total) AS b_sum
        FROM    b
        WHERE   b.iid = a.id
                AND b.id = 19
                AND b.isActive = 1
        ) b

答案 1 :(得分:1)

UPDATE a
  SET a.Wallet= a.Wallet+ tmp.Total    
FROM a 
CROSS APPLY (SELECT SUM(Total) as Total
             FROM b 
             WHERE b.Id = a.Id 
             AND   b.ID= 19
             AND b.IsActive = 1
             ) tmp

答案 2 :(得分:0)

您必须使用SUM(b.Total)和GROUP BY b.ID来获取该值才能匹配。现在,您的更新查询只是匹配它找到的第一个ID。

答案 3 :(得分:0)

希望工作正常

UPDATE a
SET a.Wallet = a.Wallet+f.valsum
FROM 
(
  SELECT  b.IID,SUM(b.Total) valsum
  FROM b
  WHERE b.IsActive = 1 AND b.ID= 19
  GROUP BY  b.IID
) f
WHERE ON a.ID = f.IID;