我正在尝试在Composer列中找到10个或更多具有NULL值的轨道的播放列表。
以下是表格
CREATE TABLE [Playlist]
(
[PlaylistId] INTEGER NOT NULL,
[Name] NVARCHAR(120),
CONSTRAINT [PK_Playlist] PRIMARY KEY ([PlaylistId])
);
CREATE TABLE [PlaylistTrack]
(
[PlaylistId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
CONSTRAINT [PK_PlaylistTrack] PRIMARY KEY ([PlaylistId], [TrackId]),
FOREIGN KEY ([PlaylistId]) REFERENCES [Playlist] ([PlaylistId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES [Track] ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE TABLE [Track]
(
[TrackId] INTEGER NOT NULL,
[Name] NVARCHAR(200) NOT NULL,
[AlbumId] INTEGER,
[MediaTypeId] INTEGER NOT NULL,
[GenreId] INTEGER,
[Composer] NVARCHAR(220),
[Milliseconds] INTEGER NOT NULL,
[Bytes] INTEGER,
[UnitPrice] NUMERIC(10,2) NOT NULL,
CONSTRAINT [PK_Track] PRIMARY KEY ([TrackId]),
FOREIGN KEY ([AlbumId]) REFERENCES [Album] ([AlbumId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([GenreId]) REFERENCES [Genre] ([GenreId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([MediaTypeId]) REFERENCES [MediaType] ([MediaTypeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
这是我到目前为止所拥有的。我认为查询逻辑很好,但这是计算空值的正确方法吗?
SELECT P.PlaylistId, P.name
FROM Playlist P
JOIN PlaylistTrack pt ON p.PlaylistId = pt.PlaylistId
JOIN Track t ON pt.TrackId = t.TrackId
GROUP BY p.PlaylistId
HAVING COUNT(t.Composer IS NULL) >=10;
答案 0 :(得分:1)
尝试比较COUNT(T.Compser) >= 10
子句中的SELECT
是错误的。这是一个比较(总是)返回一个真/假。该子查询也与您的外部查询无关。我真的很惊讶它甚至没有错误地运行。
您应该能够使用HAVING
子句,该子句用于比较聚合:
SELECT
P.PlaylistID,
P.Name
FROM
Playlist P
INNER JOIN PlaylistTrack PT ON PT.PlaylistID = P.PlaylistID
INNER JOIN Track T ON
T.TrackID = PT.TrackID AND
T.Composer IS NULL
GROUP BY
P.PlaylistID,
P.Name
HAVING
COUNT(*) >= 10
编辑:你已经改变了你的问题。使用新查询时,问题是COUNT()
将始终计算一行,无论该值是什么,除非该值为NULL
。 T.Composer IS NULL
将评估为值 - 无论是真还是假(1/0),这意味着无论T.Composer
的值如何,每一行都将计入聚合。
答案 1 :(得分:0)
而不是NULL,你只能声明像<>这样的东西。 0?或= 0?
或者至少尝试:
T.Composer为NULL或col =''
或T.Composer IsNull(col,'')=''
答案 2 :(得分:0)
我会使用left join而不是inner。这样,即使该查询中没有行,它仍将返回一行。有时这有可能破坏你的陈述,因为它不能算作空。