简体   繁体   中英

Sub-query results 'Single Row Sub-Query results more than One Row'

I have a Table Office created in SQL Terminal on Oracle 11g .


Whose 3 columns are
Ename | Bname | salary Ename | Bname | salary where:-
Ename : The name of the employer.
Bname : Boss Name
Salary : Employee salary.

The values inside the Office Table are :-

 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 .

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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