0

我需要从employee条件 onname和的表中获取记录department。如果该名称不存在任何记录并离开,那么它应该从employeefor that返回前 1 条记录department

前任:

SELECT * FROM EMPLOYEE WHERE NAME = 'SQL' AND DEPID = 1
 IF NOT EXISTS 
     SELECT TOP 1 * FROM EMPLOYEE WHERE DEPID = 1

这可以在单个查询中实现并且还考虑性能。

4

4 回答 4

1

这应该适用于 MS SQL:

SELECT TOP 1 *
FROM employee
WHERE depid = 1
ORDER BY CASE WHEN name = 'SQL' THEN 0 ELSE 1 END

对于 PostgreSQL 和 MySQL,使用:

SELECT * FROM employee
WHERE depid = 1
ORDER BY name != 'SQL'
LIMIT 1

为获得最佳性能,请在(depid, name).

于 2013-04-26T03:53:12.120 回答
1

尝试这个

SELECT TOP 1 * FROM EMPLOYEE WHERE DEPID = 1 AND 
NAME = CASE 
       WHEN EXISTS(SELECT 1 FROM EMPLOYEE WHERE DEPID = 1 AND NAME = 'SQL') 
       THEN 'SQL' ELSE NAME END
于 2013-04-26T03:57:45.177 回答
0

我假设您使用的是 SQL 服务器。

一个简单的 If exists else 逻辑将在这里工作。

If exists(SELECT 1 from employee WHERE ename='SQL' AND deptno=1)
SELECT * from employee WHERE name='SQL' AND deptno=1
else 
select top 1 * from empoyee where deptno=1
于 2013-04-26T04:17:41.653 回答
0
select top 1 * from employee where depid = 1 and not exists (select * from employee where name = 'SQL' and depid = 1)
union all
select * from employee where name = 'SQL' and depid = 1
于 2013-04-26T03:59:28.410 回答