简体   繁体   English

子查询结果“单行子查询结果超过一行”

[英]Sub-query results 'Single Row Sub-Query results more than One Row'

I have a Table Office created in SQL Terminal on Oracle 11g . 我在Oracle 11g的SQL Terminal中创建了一个表Office


Whose 3 columns are 3列是谁
Ename | Bname | salary Ename | Bname | salary where:- Ename | Bname | salary哪里:
Ename : The name of the employer. Ename :雇主名称。
Bname : Boss Name Bname :老板名字
Salary : Employee salary. Salary :员工工资。

The values inside the Office Table are :- Office Table中的值为:-

 ENAME BNAME SALARY -------------------- -------------------- ---------- Zahid Muheet 30000 Arif Muheet 20002 Ahtishaam Muheet 20002 Ayaaz Muheet 2000 Zaid Muheet 40000 Muheet Akib 40000 6 rows selected. 

I want to retrieve all those employees name( ename ) whose salary is greater or equal to his boss salary . 我想检索所有salary大于或等于其boss salary雇员姓名( ename )。

Output Should be: 输出应为:

 ENAME ------ Zaid 

I'm writing a query on my terminal 我在终端上写查询

 select emp.ename from office emp where emp.salary >= (select a.salary from office a, office b where a.ename = b.bname) 

I guess it should work but its resulting in error : 我想它应该可以工作,但是会导致错误:

ORA-01427: single-row subquery returns more than one row ORA-01427:单行子查询返回多个行

select emp.ename 
from office emp 
where emp.salary>= ( select boss.salary 
                     from office boss 
                     where emp.bname = boss.ename)

You can use a self-join for this as well 您也可以为此使用自联接

select o1.ename 
from office o1
join office o2 on o1.ename = o2.bname
where o1.salary >= o2.salary

JOIN the table with itself: 自己加入表格:

SELECT
oa.ename
FROM office AS oa
INNER JOIN office AS ob ON oa.bname = ob.ename
WHERE oa.salary >= ob.salary;

This creates a result set where everyone's salary and name and their bosses salary and name are available, and then filters it by those where the employee salary is greater then or equal to the boss's salary. 这将创建一个结果集,其中每个人的薪水和姓名以及其老板的薪水和姓名均可用,然后根据员工薪水大于或等于老板的薪水的人员进行筛选。

In a case such as this one there is no need to use a subquery, but if you absolutely have to, there is a way using a subquery as well: 在这种情况下,不需要使用子查询,但是如果绝对需要,也可以使用子查询:

SELECT
oa.ename
FROM office AS oa
WHERE oa.salary >= (SELECT ob.salary FROM office AS ob WHERE ob.ename = oa.bname)

And a 3rd approach using exists and a correlated subquery. 并且使用存在和相关子查询的第三种方法。

SELECT Emps.EName
FROM Office Emps
WHERE EXISTS (SELECT * 
              FROM Office Boss 
              WHERE Emps.BName = Boss.EName 
                and Emps.Salary >= Boss.Salary)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM