我正在尝试根据同一表中的另一行修改一列的值,因此我正在使用自连接,我得到了预期的更改,但是它选择了两行(原始和修改后的行),如果任何一列被修改,则不想选择原始行,它应只选择已修改的行,如果其值已被修改,否则应选择原始行。我创建了一个类似的模式来阐明这个问题:
create table tbl
(
id int not null,
status int not null,
name varchar null,
subject varchar null,
result varchar null
);
/* Create few records in this table */
INSERT INTO tbl VALUES(1, 1, 'A', 'sub1', 'Pending');
INSERT INTO tbl VALUES(2, 2, 'A', 'all', 'Passed');
INSERT INTO tbl VALUES(3, 1, 'B', 'sub1', 'Pending');
INSERT INTO tbl VALUES(4, 3, 'B', 'sub2', 'Failed');
INSERT INTO tbl VALUES(5, 3, 'C', 'sub1', 'Failed');
INSERT INTO tbl VALUES(6, 2, 'D', 'sub1', 'Passed');
INSERT INTO tbl VALUES(7, 1, 'E', 'sub1', 'Pending');
COMMIT;
SELECT distinct t1.id, t1.status, t1.name, t1.subject,
CASE
WHEN t1.status = 1 and t2.subject = 'all' and t2.status = 2 THEN 'Passed'
WHEN t1.status = 1 THEN 'Pending'
WHEN t1.status = 2 THEN 'Passed'
WHEN t1.status = 3 THEN 'Failed'
END AS 'result'
FROM tbl t1 join tbl t2 on t1.name = t2.name
----- 结果 ----------------------------
1|1|A|sub1|Pending
1|1|A|sub1|Passed
2|2|A|all|Passed
3|1|B|sub1|Pending
4|3|B|sub2|Failed
5|3|C|sub1|Failed
6|2|D|sub1|Passed
7|1|E|sub1|Pending
在这里,ID: 1
的行被复制了,我不再需要第一行,因为我已经根据原始表格 subject: all (ID: 2)
中的第二行修改了其 Result
列的值为 Passed
。
------ 预期结果-----------------------
1|1|A|sub1|Passed
2|2|A|all|Passed
3|1|B|sub1|Pending
4|3|B|sub2|Failed
5|3|C|sub1|Failed
6|2|D|sub1|Passed
7|1|E|sub1|Pending