【问题标题】:Table Column value in where clausewhere 子句中的表列值
【发布时间】:2021-12-05 07:59:27
【问题描述】:

我有两张桌子

员工

EmployeeId Name Job
123 David yes
124 Timothy yes
125 Maxi No
126 Abie

员工住宅

Id EmployeeId EmployeeSpclField EmployeeSpclValue
1 123 Married yes
2 123 Nationality MEX
3 123 Job Fitter
4 124 Married yes
5 124 Nationality ARG
6 125 Job Driver

我需要一个 Sql 查询,它根据 Bind 值 Employee id 返回 1 或 0,并且我需要验证以下条件

  1. 作业不应为空 2)国籍不应该为空,他应该属于MEX

那我该怎么做呢? 我正在构建这样的东西

select 1 from Employee emp ,EmployeeResidence er 
where 
employeeid=:empid and emp.job is not null and 

我正在努力包含 EmployeeSpclField 列值以检查它是否不为空并且属于 MEX

【问题讨论】:

  • 今日提示:切换到现代、明确的JOIN 语法。更容易编写(没有错误),更容易阅读(和维护),并且在需要时更容易转换为外连接。
  • 这是mysql还是oracle?
  • 我已经删除了 mysql 标签

标签: sql oracle oracle11g


【解决方案1】:

我可能会避免加入,而是在这里使用存在逻辑:

SELECT e.*
FROM Employee e
WHERE Job IS NOT NULL AND
      EXISTS (SELECT 1 FROM EmployeeResidence er
              WHERE er.EmployeeId = e.EmployeeId AND
                    er.EmployeeSpclField = 'Nationality' AND
                    er.EmployeeSpclValue = 'MEX');

【讨论】:

    【解决方案2】:

    选择一个 0/​​1 标志

    select case when exists (
        select 1 
        from Employee emp 
        join EmployeeResidence er 
          on emp.employeeid = er.employeeid and er.EmployeeSpclField = 'Nationality' and er.EmployeeSpclValue = 'MEX'
        where emp.employeeid=:empid and emp.job is not null ) then 1
       else 0 end flag 
    from dual;
    

    【讨论】:

      【解决方案3】:

      试试这个:

      Select
      e.EmployeeID,
      case when er.EmployeeID is null then 0 else 1 end as return_val
      from
      Employee e
      left outer join
      (select EmployeeId,
       max(case when EmployeeSpclField='Married' then EmployeeSpclValue else NULL end) as married,
       max(case when EmployeeSpclField='Nationality' then EmployeeSpclValue else NULL end) as Nationality,
       max(case when EmployeeSpclField='Job' then EmployeeSpclValue else NULL end) as Job
      from 
       EmployeeResidence
      group by
      EmployeeId) er
      on e.EmployeeId=er.EmployeeId
      and e.Job is not null 
      and (er.Nationality is not null and er.Nationality ='MEX')
      

      【讨论】:

        【解决方案4】:

        一种选择可能是使用条件聚合来计算所需条件

        SELECT SIGN(NVL(SUM(CASE WHEN er.EmployeeSpclField = 'Nationality' 
                                  AND er.EmployeeSpclValue = 'MEX' 
                                  AND e.Job IS NOT NULL THEN 1 ELSE 0 END),0)) 
            AS Result
          FROM Employee e
          JOIN EmployeeResidence er
            ON er.EmployeeId = e.EmployeeId
         WHERE e.EmployeeId = :empid
        

        使用SIGN() 函数时,考虑到EmployeeSpclField 列的Nationality 值可能与EmployeeId 列的任何值有重复记录。

        Demo

        【讨论】:

          猜你喜欢
          • 2022-01-19
          • 1970-01-01
          • 1970-01-01
          • 2015-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多