MySQL SELECT 子句中的相关子查询

MySQL correlated sub-query in SELECT clause

我正在尝试在 MySQL 查询的 SELECT 子句中执行相关子查询。如何在子查询的 WHERE 子句中的另一列中使用一行的值?

我一直在引用 this webpage 的 "Correlated Sub-Query Example" 部分,但由于某些原因,我的查询无法正常工作。

这是我的代码:

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

基本上,我正在尝试创建一个 table 来显示每年创建的每种类型的系统数量。当我 运行 在 MySQL Workbench 中查询时,它 运行 直到数据库连接过期。我看不出此查询与我引用的网站上的查询有何不同。

如有任何帮助,我们将不胜感激!如果似乎有更好的方法可以解决这个问题,我也对这些想法持开放态度。谢谢!

可能是您有范围问题尝试对每一行使用内部联接而不是子查询

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 

使用 Group By 语句代替子查询。随着添加更多行,子查询会使您的查询 运行 变慢。试试这个查询来获取每年每种类型制造的系统数量:

SELECT
    Year, 
    SYSTEMTYPE, 
    COUNT(*) as Total_systems_per_type_per_year
FROM systems
WHERE Year IS NOT NULL
GROUP BY Year, SYSTEMTYPE

这可能是查询性能的问题。这样的子查询需要对每一行执行,因此可能需要很长时间运行。可以使用 group by:

简化查询
select year, count(*) from systems
where Year is not null and systemtype = 'handled'
group by Year

关于评论的更新:

what if I want to add more columns for different types of systems other than just the one type?

使用查询:

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