在多个条件下加入每个条件结果

时间:2018-10-09 06:15:29

标签: join conditional-statements

我想获取每个条件结果的详细信息,如联接中使用的true或false。例如下面的情况

a:visited { outline: none; }
现在让我们说第一个连接条件emp_id为true,其余条件为false。我想输出为

select emp.emp_id,emp.emp_name,hr.department,hr.salary 
from employee emp left outer join HR
on emp.empId=HR.emp_id 
and emp.emp_name=HR.emp_name
and emp.department=hr.department
and emp.salary=hr.salary;

如果前两个条件为真,则输出应为

emp.emp_id,emp.emp_name,hr.department,hr.salary

true,false,false,false

,依此类推。此处仅作为示例,请忽略数据库设计。谢谢

咖啡馆

2 个答案:

答案 0 :(得分:0)

这可能与您要在此处执行的操作类似:

SELECT
    CASE WHEN EXISTS (SELECT 1 FROM HR WHERE emp.empId = HR.empID)
         THEN 'true' ELSE 'false' END AS emp_id,
    CASE WHEN EXISTS (SELECT 1 FROM HR WHERE emp.emp_name = HR.emp_name)
         THEN 'true' ELSE 'false' END AS emp_name,
    CASE WHEN EXISTS (SELECT 1 FROM HR WHERE emp.department = HR.department)
         THEN 'true' ELSE 'false' END AS department,
    CASE WHEN EXISTS (SELECT 1 FROM HR WHERE emp.salary = HR.salary)
         THEN 'true' ELSE 'false' END AS salary
FROM employee emp;

每个带有CASE语句的EXISTS语句都在employee表中进行记录,以查看HR表是否可以找到至少一条匹配的记录,该特定列。

请注意,此答案可能无法反映实际的联接,其中employee中的记录可能与HR中的多个记录相匹配。但是,在这种情况下,对于单独的单个列匹配或不匹配的含义没有很好地定义。

答案 1 :(得分:0)

也许您可以尝试:

SELECT CASE WHEN emp.emp_id = HR.emp_id THEN 'True' ELSE 'False' as [emp_id],
CASE WHEN emp.emp_name = HR.emp_name THEN 'True' ELSE 'False' as [emp_name],
CASE WHEN emp.department = HR.department THEN 'True' ELSE 'False' as [department],
CASE WHEN emp.salary = HR.salary THEN 'True' ELSE 'False' as [salary],
from employee emp left outer join HR
on emp.empId=HR.emp_id 
and emp.emp_name=HR.emp_name
and emp.department=hr.department
and emp.salary=hr.salary