Reputation: 412
I'm trying to execute a correlated sub-query in the SELECT
clause of a MySQL query. How do I use the value of a row in another column inside the WHERE
clause of my subquery?
I've been referencing the "Correlated Sub-Query Example" section of this webpage, but for some reason my query is not working the same.
Here is my code:
SELECT Year,
( SELECT COUNT(*)
FROM systems
WHERE SYSTEMTYPE = 'handheld' AND Year = sys.Year
) as handheld,
( SELECT COUNT(*)
FROM systems
WHERE SYSTEMTYPE = 'console' AND Year = sys.Year
) as console,
FROM systems as sys
WHERE Year IS NOT NULL
Basically, I'm trying to create a table that shows how many systems of each type were created for each year. When I run that query in MySQL Workbench it runs until the database connection expires. I can't see how this query is much different than the one on the website I am referencing.
Any help would be greatly appreciated! If it seems there is a better way I could go about this, I am open to those ideas as well. Thank you!
Upvotes: 1
Views: 3637
Reputation: 37500
This may be issue of performance of a query. Such subquery needs to be executed for each row, thus it may take long to run. The query can be simplified by using group by
:
select year, count(*) from systems
where Year is not null and systemtype = 'handled'
group by Year
UPDATE regarding comment:
what if I want to add more columns for different types of systems other than just the one type?
Use query:
select year,
sum(case when systemtype = 'handled' then 1 else 0 end) handled,
sum(case when systemtype = 'console' then 1 else 0 end) console
from systems
where Year is not null
group by Year
Upvotes: 3
Reputation: 249
Use Group By statement instead of subqueries. Subqueries will make your query run much slower as more rows are added. Try this query to get number of systems made per type and per year:
SELECT
Year,
SYSTEMTYPE,
COUNT(*) as Total_systems_per_type_per_year
FROM systems
WHERE Year IS NOT NULL
GROUP BY Year, SYSTEMTYPE
Upvotes: 2
Reputation: 133400
Could be you have a scope issue try use a inner join instead of a subquery for each rows
SELECT sys.Year, t.my_count
FROM systems as sys
INNER JOIN
( SELECT Year, COUNT(*) my_count
FROM systems
WHERE SYSTEMTYPE = 'handheld' AND Year = sys.Year
GROUP BY year
) t on t.year = sys.year
WHERE sys.Year IS NOT NULL
Upvotes: 2