这是一个有趣的问题。我相信以下可以是一个直观而漂亮的解决方案(我使用desc_作为列名,而不是desc,这是一个保留字):
select (select desc_ from ErrorCodes x where x.type_code = a.typeCode) desc_
from ErrorXML a
where (select desc_ from ErrorCodes x where x.type_code = a.typeCode) is not null
order by row_index
limit 1;
如果您还需要处理查询没有返回行的情况,那么对于 MySQL,以下语法就足够了。对于其他数据库,您可以使用 isnull、nvl 等类似的封装:
select ifnull((select (select desc_ from ErrorCodes x where x.type_code = a.typeCode) desc_ from ErrorXML a where (select desc_ from ErrorCodes x where x.type_code = a.typeCode) is not null order by row_index limit 1), 'UNKNOWN');
为了测试,我使用了以下脚本并且似乎可以正常工作:
create database if not exists stackoverflow;
use stackoverflow;
drop table if exists ErrorCodes;
create table ErrorCodes
(
type_code varchar(2),
desc_ varchar(10)
);
insert into ErrorCodes(type_code, desc_) values
('01', 'Error101'),
('02', 'Error99'),
('03', 'Error120');
drop table if exists ErrorXML;
create table ErrorXML
(
row_index integer,
typeCode varchar(2)
);
insert into ErrorXML(row_index, typeCode) values
('1', '87'),
('2', '02'),
('3', '01');
Final-1 引用:在生成表格时,尽量使用相同的列名。 IE。我建议ErrorXML 使用type_code 而不是typeCode。
最后引用:我选择在 SQL 中使用小写字母,因为在强调重点的同时应该使用大写字母。我也推荐这种风格。