DDL:
CREATE TABLE [Tags](
[TagID] [bigint] IDENTITY(1,1) NOT NULL,
[Tag] [nvarchar](100) NOT NULL,
PRIMARY KEY CLUSTERED
(
[TagID] ASC
),
CONSTRAINT [UC_Tags] UNIQUE NONCLUSTERED
(
[Tag] ASC
)
)
GO
CREATE TABLE [Videos](
[VideoID] [bigint] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](100) NOT NULL,
[isActive] [bit] NOT NULL,
PRIMARY KEY CLUSTERED
(
[VideoID] ASC
),
CONSTRAINT [UC_Videos] UNIQUE NONCLUSTERED
(
[Title] ASC
)
)
GO
CREATE TABLE [VideoTags](
[VideoID] [bigint] NOT NULL,
[TagID] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED
(
[VideoID] ASC,
[TagID] ASC
)
)
GO
ALTER TABLE [VideoTags] WITH CHECK ADD FOREIGN KEY([TagID])
REFERENCES [Tags] ([TagID])
GO
ALTER TABLE [VideoTags] WITH CHECK ADD FOREIGN KEY([VideoID])
REFERENCES [Videos] ([VideoID])
GO
- nvarchar. "" .
- id IDENTITY
- I would make the Tag and Title columns unique. You do not want to duplicate headings or tags
- I would make all these columns non-empty. It makes no sense to have a video or tag with an unknown name, and video inactive and inactive is never "possibly" or "unknown."
- I added a primary key to VideoTags to prevent duplication.
For an SQL query, I would try the following. I cannot be sure what you want without test data:
;
WITH VIDEO_TAG_COUNTS(VideoID,TagCount)
AS
(
SELECT v.VideoID, COUNT(*)
FROM Videos V
INNER JOIN VideoTags VT ON V.VideoID = VT.VideoID
GROUP BY V.VideoID
)
SELECT V.VideoID, V.Title
FROM Videos V
INNER JOIN VIDEO_TAG_COUNTS VTC ON V.VideoID = VTC.VideoID
WHERE V.isActive = 1
ORDER BY VTC.TagCount
source
share