Sql 需要从查找表中获取值
我有一个带有ecode、emp ID(一些值)的表-X 有两个查找表 查找表1仅包含emp ID详细信息(我感兴趣) 所以当我加入时,我得到了所有需要的值(这是一部分) 我的结果将是Sql 需要从查找表中获取值,sql,Sql,我有一个带有ecode、emp ID(一些值)的表-X 有两个查找表 查找表1仅包含emp ID详细信息(我感兴趣) 所以当我加入时,我得到了所有需要的值(这是一部分) 我的结果将是 37 10 47 20 第二部分是, 那些不满足连接条件的应该在表2中查找,表中有 2列 ecode, other_codes 37 xxx 47 YYY 57 AAA 所以当30进来时,我想返回AAA,我的最终数据集应该是 37, 10 47,20 57 AAA 谢谢你的帮助 谢谢您可以左键联接两个表
37 10
47 20
第二部分是,
那些不满足连接条件的应该在表2中查找,表中有
2列
ecode, other_codes
37 xxx
47 YYY
57 AAA
所以当30进来时,我想返回AAA,我的最终数据集应该是
37, 10
47,20
57 AAA
谢谢你的帮助
谢谢您可以左键联接两个表和用例语句,以便从一个表或另一个表中选择值 我创建了一个db小提琴,根据您的描述,我认为它可以说明您的情况: 这是留给后代的密码。要设置表格,请执行以下操作:
CREATE TABLE tableX (
eCode int,
employeeId int
);
INSERT INTO tableX (eCode, employeeId) VALUES (37, 10);
INSERT INTO tableX (eCode, employeeId) VALUES (47, 20);
INSERT INTO tableX (eCode, employeeId) VALUES (57, 30);
CREATE TABLE employeeIds (employeeId int);
INSERT INTO employeeIds (employeeId) VALUES (10);
INSERT INTO employeeIds (employeeId) VALUES (20);
CREATE TABLE otherCodes (
eCode int,
other_codes varchar(10)
);
INSERT INTO otherCodes (eCode, other_codes) VALUES (37, 'XXX');
INSERT INTO otherCodes (eCode, other_codes) VALUES (47, 'YYY');
INSERT INTO otherCodes (eCode, other_codes) VALUES (57, 'AAA');
基于此架构的查询:
SELECT
tx.eCode,
CASE WHEN ei.employeeId IS NULL THEN oc.other_codes ELSE ei.employeeId END as 'result'
FROM tableX tx
LEFT JOIN employeeIds ei ON tx.employeeId = ei.employeeId
LEFT JOIN otherCodes oc ON tx.eCode = oc.eCode;
如果您可以提供SQL(用于创建数据和您迄今为止所尝试的内容)或一个工作示例(例如..),这将非常有用。请参阅刚才的左键,第一次使用第一个表连接,第二次使用ecode上的第二个表连接为null
CREATE TABLE tableX (
eCode int,
employeeId int
);
INSERT INTO tableX (eCode, employeeId) VALUES (37, 10);
INSERT INTO tableX (eCode, employeeId) VALUES (47, 20);
INSERT INTO tableX (eCode, employeeId) VALUES (57, 30);
CREATE TABLE employeeIds (employeeId int);
INSERT INTO employeeIds (employeeId) VALUES (10);
INSERT INTO employeeIds (employeeId) VALUES (20);
CREATE TABLE otherCodes (
eCode int,
other_codes varchar(10)
);
INSERT INTO otherCodes (eCode, other_codes) VALUES (37, 'XXX');
INSERT INTO otherCodes (eCode, other_codes) VALUES (47, 'YYY');
INSERT INTO otherCodes (eCode, other_codes) VALUES (57, 'AAA');
SELECT
tx.eCode,
CASE WHEN ei.employeeId IS NULL THEN oc.other_codes ELSE ei.employeeId END as 'result'
FROM tableX tx
LEFT JOIN employeeIds ei ON tx.employeeId = ei.employeeId
LEFT JOIN otherCodes oc ON tx.eCode = oc.eCode;