Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subquery using IN clause

----------
User
----------
user_ID(pk)
UserEmail

----------
Employer1
----------
Emp1ID(pk)
Emp1NO

----------
Employer2
----------
Emp2ID(pk)
Emp2NO

----------
Project
----------
ProjEmpID
ProjEmpMGRID

I need to display User Email ID. The relation between the table goes like this: In the Employer(1&2) table EmpID contains the value of UserID in the User table.

the Employer No relates to the values from the Project table. EmpNo contains values from ProjEmpID, ProjEmpMGRID.

 select u.user_email from users u, Employer emp 
    where emp.Emp1ID =  u.user_id and 
    emp.Emp1NO IN
    (select ProjEmpID,ProjEmpMGRID from project)
union 
  select u.user_email from users u, Employer emp 
    where emp.Emp2ID =  u.user_id and 
    emp.Emp2NO IN
    (select ProjEmpID,ProjEmpMGRID from project)

but i get error in the subquery stating too many parameters on the IN clause.Is there any other way i could rewrite the query to get result. any help would be appreciated.

like image 323
jero Avatar asked Jun 28 '26 21:06

jero


2 Answers

You can only return one column from your subquery. If you just want both the employee ID and manager ID consider a union query as your subquery:

    emp.Emp2NO IN
(select ProjEmpID from project
 union
 select ProjEmpMGRID from project)

or rewriting to use two IN queries with separate subqueries for each.

like image 199
Eric Hauser Avatar answered Jun 30 '26 12:06

Eric Hauser


Eric Hauser is correct - you can't specify two columns in SELECT contained in an IN clause to one column outside.

That said, I re-wrote your query so you don't need to use UNIONs at all:

SELECT DISTINCT u.user_email
  FROM USERS u
  JOIN EMPLOYER e ON u.user_id IN (e.emp1id, e.emp2id) 
  JOIN PROJECT p ON e.emp1no IN (p.projempid, p.projempmgrid)
                 OR e.emp2no IN (p.projempid, p.projempmgrid)

I also changed the query to use ANSI-92 JOIN syntax - your original uses ANSI-89.

like image 39
OMG Ponies Avatar answered Jun 30 '26 12:06

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!