我有张桌子:
DROP TABLE TBL_A;
CREATE TABLE TBL_A
(
number_id int,
country varchar(50),
status varchar(50),
number_of_days int,
datetime date
);
INSERT INTO TBL_A
VALUES (121144, 'USA', 'CLICKED',2, '2021-10-09'),
(121144, 'USA', 'CLAIMED',2, '2021-10-10'),
(121144, 'USA', 'BOUGHT',2, '2021-10-11'),
(121111, 'CAD', 'CLICKED',3, '2021-10-09'),
(121111, 'CAD', 'CLAIMED',3, '2021-10-10'),
(121111, 'CAD', 'BOUGHT',3, '2021-10-11'),
(121133, 'AUS', 'CLICKED',5, '2021-10-09'),
(121133, 'AUS', 'CLAIMED',5, '2021-10-10'),
(121133, 'AUS', 'BOUGHT',5, '2021-10-11');我还有一张桌子:
DROP TABLE TBL_B;
CREATE TABLE TBL_B
(
number_id int,
country varchar(50),
status varchar(50),
number_of_days int,
datetime date
);
INSERT INTO TBL_B
VALUES (121144, 'USA', 'CLICKED',6, '2021-10-20'),
(121111, 'CAD', 'BOUGHT',10, '2021-10-21'),
(121133, 'AUS', 'CLAIMED',5, '2021-10-02');我希望选择TBL_A中的所有内容,但如果在TBL_B中找到相同的number_id和状态,则只有在日期时间较高的情况下才选择TBL_B中的值。
有办法这样做吗?在上面的例子中,只有USA&CAD和CAD& be应该被“更新”,因为它们在第二个表中的值有更长的日期时间,其余的记录应该来自第一个表。
到目前为止,这就是我所拥有的,但在完成它时遇到了困难:
select
number_id,
country,
status,
number_of_days,
datetime date
from
TBL_A A
left join
(select
number_id,
country,
status,
number_of_days,
datetime date
from
TBL_B) on A.NUMBER_ID = B.NUMBER_ID
and a.STATUS = b.STATUS发布于 2021-12-07 19:03:52
此查询只给出结果,当ID、状态在两个表中,并且表"TBL_B“中的日期大于表"TBL_A”中的等效日期时
SELECT
B.* --everything from B according to WHERE restrict
FROM
TBL_A as A,
TBL_B as B
WHERE
A.number_id = B.number_id
AND A.status = B.status
AND A.datetime < B.datetime 当您还需要来自TBL_A的结果时,您可以使用set操作符(例如-& UNION)扩展这个查询。
(
SELECT
A.*
FROM
TBL_A as A
MINUS --everything from "A", which is not included in "B"
SELECT
B.*
FROM
TBL_A as A,
TBL_B as B
WHERE
A.number_id = B.number_id
AND A.status = B.status
AND A.datetime < B.datetime
)
UNION ALL -- Add the "B" results
SELECT
B.* -- everything from "B" according to WHERE restrict
FROM
TBL_A as A,
TBL_B as B
WHERE
A.number_id = B.number_id
AND A.status = B.status
AND A.datetime < B.datetime
;https://stackoverflow.com/questions/70265528
复制相似问题