使用HAVING COUNT的SQL子查询

时间:2013-11-22 21:02:19

标签: mysql sql

我的问题是:如何在乐队:“子弹队”录制的录音室中展示至少录制过一个标题的每位艺术家的名字?

我已经制定了以下查询:

select ar.artistname, ti.titleid from artists ar
where exists
(
select 0
from titles ti where ti.artistid = ar.artistid
and exists
(
select 0
from studios s
where s.studioid = ti.studioid
and ar.artistname = 'The Bullets'
)
);

但是,我需要包括HAVING COUNT(ti.titleid)> 0以满足这一部分,“每个艺术家在问题中记录了至少一个标题”。

我也不确定如何匹配至少录制一个工作室的艺术家名称“The Bullets”。

艺术家表重新列出以下内容:

Artists
-------
ArtistID, ArtistName, City

“曲目”表重新列出以下内容:

Tracks
------
TitleID, ArtistID, StudioID

“工作室”表格重新考虑以下内容:

Studios
-------
StudioID, StudioName, Address

我还必须指定我不能使用联接,例如,性能偏好。

3 个答案:

答案 0 :(得分:4)

也许是这样的?

select ArtistName from Artists where ArtistID in (
  select ArtistID from Tracks where StudioID in (
    select StudioID from Tracks where ArtistID in (
      select ArtistId from Artists where ArtistName='The Bullets'
    )
  )
)

我不明白你为什么认为需要having

答案 1 :(得分:2)

子弹记录的工作室

SELECT StudioID
FROM Sudios S
JOIN Tracks T ON S.StudioID = S.StudioID
JOIN Artists A ON T.ArtistID = A.ArtistID AND A.ArtistName = 'The Bullets'

每位录制在那里的艺术家

SELECT A1.ArtistName, A1.City
FROM Artist A1
JOIN Tracks T1 ON T1.ArtistID = A2.ArtistID
WHERE T1.SudioID IN 
(
  SELECT StudioID
  FROM Sudios S
  JOIN Tracks T ON S.StudioID = S.StudioID
  JOIN Artists A ON T.ArtistID = A.ArtistID AND A.ArtistName = 'The Bullets'
) T

答案 2 :(得分:0)

这两个要求非常愚蠢 - 使用HAVING COUNT(*)> 0并且没有连接。我从来没有听说过在连接上选择子查询来提高性能。

但是,我认为此查询符合这些要求。

SELECT a.ArtistName FROM Artist a
WHERE EXISTS
(
    SELECT t1.ArtistId FROM Track t1
    WHERE t1.ArtistId = a.ArtistId
    AND EXISTS
    (
         SELECT * FROM Track t2
         WHERE t1.StudioId = t2.StudioID
         AND t2.ArtistName = 'The Bullets'
    )
    GROUP BY t1.ArtistId, t1.StudioId
    HAVING COUNT(*) > 0
);