sql - 如何更有效地执行查询,返回一个 ID 在其他两个表中出现的次数?

标签 sql derby

我从其他来源找到了一些解决方案,但似乎没有一个对我有效。我正在使用 derby,而我当前的解决方案需要一分钟多的时间来执行!

我试图找到属于给定艺术家的歌曲和专辑的数量,并将这些数字显示在艺术家姓名和 ID 旁边的 2 个单独列中。前任:

ID    Name        Songs    Albums
425   J. Smith    0        0
314   A. Payne    32       3
412   K. Thomas   423      35

艺术家表有artist_id,歌曲表有song_id 和album_id,专辑表有album_id 和artist_id。 table 并不小。艺术家有大约 1,100 条记录,歌曲大约有 73,000 条,专辑大约有 7,000 条。

这是我目前的解决方案:
select ar.artist_id, ar.artist_name, count(s.song_id), count(distinct(al.album_id))
from artist ar left outer join 
    (album al inner join song s 
    on al.album_id = s.album_id)
on ar.artist_id = al.artist_id 
group by ar.artist_id, ar.artist_name

有没有办法让这个查询性能更好? ID 列都是它们各自表中的主键,所以如果我理解正确的话,它们应该已经在 derby 中建立了索引。

最佳答案

此查询使用派生表来获取歌曲和专辑计数

select ar.artist_id, ar.artist_name, 
    coalesce(t1.song_cnt,0), coalesce(t2.album_cnt,0)
from artist ar left join (
    select artist_id, count(*) song_cnt
    from song group by artist_id
) t1 on t1.artist_id = ar.artist_id 
left join (
   select artist_id, count(*) album_cnt
   from album group by artist_id
) t2 on t2.artist_id = ar.artist_id

您可能想要研究将计数本身存储在您的数据库中并使用触发器更新它们。

关于sql - 如何更有效地执行查询,返回一个 ID 在其他两个表中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873800/

相关文章:

database-schema - 如何创建 derby 用户

java - 没有名为 EntityManager 的持久性提供程序

mysql - 无法在 mysql 上创建查询

sql - PostgreSQL 查询以查找具有匹配数据的行并组合这些行中的列

mysql - SQL 查找 4 月份最畅销产品

mysql - 在不知道其名称的情况下删除 MySQL 列索引

maven - InvocationTargetException:javax/persistence/Persistence

java - HIbernate Maven项目:没有名为EntityManager的持久性提供程序

java - 最终用户对 Java DB 的要求

sql - MS SQL - 仅选择一行作为 ID