我无法让这个查询按照我想要的方式工作。我有两个数据几乎相同的表,但希望一个表覆盖另一个表(如果存在)。举个例子比尝试解释更容易:
有一个未调整的余额表:
所需的输出采用未调整的余额,并在其之上应用任何现有调整(如果 is_current=1)...本质上替换该行,但仍保留原始未调整的 current_balance。
所需的输出将是这样的:
这是我当前的查询,它没有按照我想要的方式工作...它正在翻转值并缺少 current_balance。我已经尝试了几个小时但无法到达任何地方:
SELECT
*
FROM
(
SELECT
balance_adjustments.name,
balance_adjustments.user_id,
balance_adjustments.amount_owed,
balance_adjustments.when_to_pay,
balance_adjustments.current_balance
FROM
balance_adjustments
WHERE
balance_adjustments.when_to_pay = '2018-11-05'
AND balance_adjustments.is_current = true
UNION ALL
SELECT
unadjusted_balance.name,
unadjusted_balance.user_id,
unadjusted_balance.amount_owed,
unadjusted_balance.when_to_pay,
unadjusted_balance.current_balance
FROM
unadjusted_balance
LEFT OUTER JOIN balance_adjustments ON balance_adjustments.user_id = unadjusted_balance.user_id
AND balance_adjustments.name = unadjusted_balance.name
AND balance_adjustments.when_to_pay = unadjusted_balance.when_to_pay
AND balance_adjustments.is_current = true
WHERE
unadjusted_balance.when_to_pay = '2018-11-05'
AND balance_adjustments.name IS NULL
) AS table1
一些额外的命令可以帮助任何人设置此场景以进行测试:
CREATE TABLE balance_adjustments
(
name varchar(30),
user_id varchar(30),
amount_owed float,
when_to_pay datetime,
current_balance float,
is_current boolean
);
CREATE TABLE unadjusted_balance
(
name varchar(30),
user_id varchar(30),
amount_owed float,
when_to_pay datetime,
current_balance float
);
insert into balance_adjustments values ('ricardo', '82340001', 100.00, '2018-11-05', null, 1)
insert into balance_adjustments values ('ricardo', '82340001', 33.00, '2018-11-05', null, 0)
insert into unadjusted_balance values ('joseph', '82340000', 2400.00, '2018-11-05', 4049.00)
insert into unadjusted_balance values ('ricardo', '82340001', 899.00, '2018-11-05', 500.00)
感谢您的帮助
最佳答案
如果您只想将 amount_owed
替换为 balance_adjustments
表中的值,其中 is_current
为 1(我假设有仅这些值之一),那么简单的 LEFT JOIN
和 COALESCE
就足够了。 COALESCE
确保 balance_adjustments
表中不匹配行的任何 NULL
值被 unadjusted_balances
中的原始值替换 table 。从您的问题中不清楚您是否也想替换 when_to_pay
字段,我假设您在此查询中已替换。如果不这样做,只需将 COALESCE(ba.when_to_pay, ub.when_to_pay) ASwhen_to_pay
替换为 ub.when_to_pay
。
SELECT ub.name, ub.user_id,
COALESCE(ba.amount_owed, ub.amount_owed) AS amount_owed,
COALESCE(ba.when_to_pay, ub.when_to_pay) AS when_to_pay,
ub.current_balance
FROM unadjusted_balance ub
LEFT JOIN balance_adjustments ba ON ba.user_id = ub.user_id AND ba.is_current
ORDER BY ub.name
输出:
name user_id amount_owed when_to_pay current_balance
joseph 82340000 2400 2018-11-05 00:00:00 4049
ricardo 82340001 100 2018-11-05 00:00:00 500
关于mysql - SQL 连接两个表,但如果第一个表存在于第二个表中,则覆盖第一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53162093/