Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this database query?

I have the following tables in a database (i'll only list the important attributes):

Person(ssn,countryofbirth)
Parents(ssn,fatherbirthcountry)
Employment(ssn, companyID)
Company(companyID, name)

My task is this: given fatherbirthcountry as input, output the names of companies where persons work whose countryofbirth match the fatherbirthcountry input.

I pretend that the fatherbirthcountry is Mexico and do this:

SELECT name 
FROM Company 
WHERE companyid = (SELECT companyid  
                   FROM Employment 
                   WHERE ssn = (SELECT ssn 
                                FROM Person 
                                WHERE countryofbirth = 'Mexico');

but it is giving me an error:

>Scalar subquery is only allowed to return a single row.

am I completely off track? Can anybody please help?

like image 206
101010110101 Avatar asked Dec 22 '22 04:12

101010110101


2 Answers

The problem is that your subqueries are returning multiple results, so you have to use where in vs. =.

Change where ssn = to where ssn in, and where companyid = to where companyid in.

like image 140
Mike Cialowicz Avatar answered Jan 02 '23 19:01

Mike Cialowicz


try using the IN keyword not '='.

try changing your query to this

SELECT name FROM Company WHERE companyid IN (SELECT companyid
FROM Employment WHERE ssn IN (SELECT ssn FROM Person WHERE countryofbirth = 'Mexico');

like image 44
Chris Avatar answered Jan 02 '23 17:01

Chris