I have one query that returns multiple rows, and another query in which I want to set criteria to be either one of values from those multiple rows , so basicly I want the subquery to look something like this:
select *
from table
where id= (multiple row query);
Where multiple row query
returns multiple rows. So if the values from those rows are 1,2,3 then I want to set id to be 1 or 2 or 3.
There are essentially two options to take. The first is to rewrite the query so that the subquery will only return a single row, thus eliminating the source of the error. This will require a user to rethink how they wish to acquire the data that they were initially searching for.
Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).
This is not permitted when the subquery follows =, != , <, <= , >, >= or when the subquery is used as an expression.
=
can be used when the subquery returns only 1 value.
When subquery returns more than 1 value, you will have to use IN
:
select *
from table
where id IN (multiple row query);
For example:
SELECT *
FROM Students
WHERE Marks = (SELECT MAX(Marks) FROM Students) --Subquery returns only 1 value
SELECT *
FROM Students
WHERE Marks IN
(SELECT Marks
FROM Students
ORDER BY Marks DESC
LIMIT 10) --Subquery returns 10 values
You can use in()
:
select *
from table
where id in (multiple row query)
or use a join:
select distinct t.*
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>
The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.
Use MAX
in your SELECT
query to return one value… EXAMPLE
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT MAX(student_id) FROM student), (SELECT MAX(syr_id) FROM school_year))
instead of
INSERT INTO school_year_studentid (student_id,syr_id) VALUES
((SELECT (student_id) FROM student), (SELECT (syr_id) FROM school_year))
try it without MAX it will return more than one value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With