2013-07-23 163 views
1
SELECT TOP 4000 Users.Id 
    FROM Users 
    JOIN Streams ON Users.Id = Streams.UserId 
    JOIN Playlists ON Streams.Id = Playlists.StreamId 
    WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' 
    // Doesn't work 
    HAVING COUNT(1) = (
    SELECT COUNT(Playlists.Id) 
    FROM Playlists WHERE Playlists.StreamId = Streams.Id 
) 

我試圖選擇所有隻有Streams有1個播放列表和1個播放列表有一個Guid.Empty的FirstItemId的用戶。我試圖做一些數據庫維護和刪除已創建但從未使用的帳戶。只選擇一個孩子的父母

我已經得到了查詢的第一部分工作得很好,但我不知道我可以如何正確應用我的「只有1個孩子」過濾器。

+0

你能描述用戶,溪流,和播放列表表? –

+0

用戶與Streams有一對多的關係。流與播放列表有一對多的關係。如果有幫助,我會添加表格的屏幕截圖? –

+0

您的問題只是count關鍵字?也就是說,在你的子句中,你能比較子查詢與「1」而不是「COUNT(1)」嗎? – Zec

回答

1

嘗試下面的查詢,選擇活動用戶進行

SELECT TOP 4000 Users.Id 
FROM Users 
JOIN Streams ON Users.Id = Streams.UserId 
JOIN Playlists ON Streams.Id = Playlists.StreamId 
WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' 
AND (SELECT COUNT(Playlists.Id) FROM Playlists WHERE Playlists.StreamId = Streams.Id) =1 
3

我想你可以用WHERE很容易地做到這一點NOT EXISTS子句

SELECT TOP 4000 Users.Id 
    FROM Users 
    JOIN Streams ON Users.Id = Streams.UserId 
    JOIN Playlists ON Streams.Id = Playlists.StreamId 
    WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' 
    AND NOT EXISTS (
    SELECT 1 FROM Playlists 
    WHERE Playlists.StreamId <> Playlists.FirstItemId 
) 
) 
+0

這就近了。我想它給了我一個關於如何去做的想法。謝謝! –

+0

@seanmk +1使我的答案更容易編寫 – xagyg

1

@seanmk有一個好主意......像這樣...下面

SELECT TOP 4000 Users.Id 
    FROM Users 
    JOIN Streams ON Users.Id = Streams.UserId 
    JOIN Playlists p ON Streams.Id = p.StreamId 
    WHERE p.FirstItemId = '00000000-0000-0000-0000-000000000000' 
    AND NOT EXISTS (
    SELECT 1 FROM Playlists q 
    WHERE q.Id = p.Id 
     AND q.FirstItemId <> p.FirstItemId 
) 
) 
1

查詢應符合你的要求。

SELECT TOP 4000 Users.Id 
FROM Users 
JOIN Streams ON Users.Id = Streams.UserId 
JOIN Playlists ON Streams.Id = Playlists.StreamId 
WHERE Playlists.FirstItemId = '00000000-0000-0000-0000-000000000000' 
AND Playlists.StreamId IN (
    SELECT Playlists.StreamId 
    FROM Playlists 
    GROUP BY Playlists.StreamId 
    HAVING COUNT(*) = 1 
) 
0

沒有子querys,具有,或組由:

SELECT TOP 4000 Users.Id 
FROM Users 
INNER JOIN Streams ON Users.Id = Streams.UserId 
INNER JOIN Playlists p1 ON Streams.Id = p1.StreamId AND p1.FirstItemId = '00000000-0000-0000-0000-000000000000' 
LEFT JOIN Playlists p2 ON Streams.ID = p2.StreamID and p2.FirstItemID <> '00000000-0000-0000-0000-000000000000' 
WHERE p2.StreamID IS NULL 
0

這是着眼於問題的另一種方式。除了使用exists,它採用聚集的條件:

select top 4000 Id 
from (SELECT u.Id, 
      min(FirstItemId) as MinFI, 
      max(FirstItemId) as MaxFI, 
      min(p.Id) as minpid, 
      max(pid) as maxpid 
     FROM Users u JOIN 
      Streams s 
      ON u.Id = s.UserId join 
      Playlists p 
      ON s.Id = p.StreamId 
     group by u.id 
    ) u 
where MinFi = MaxFi and MinFi = '00000000-0000-0000-0000-000000000000' and 
     minpid = maxpid; 

我不知道哪個版本會表現得更好。這只是查看問題的一種替代方法。