警告:我已经知道,这真是令人费解和可怕。但是,我没有构建数据库,我只需要使用它,我无法更改数据库架构。
以下是我正在使用的表格:
射击
ShotID(身份),FilmID(FK),ShotNumber,....,。
代码
TagID(身份),姓名
TaggedShot
TaggedShotID(身份),ShotID(FK),TagID(FK),TagComment
TaggedCategory
TagID(FK),CategoryID(FK)
我的存储过程:
[dbo].[SelectAllTagNames]
@filmID int,
@tagCategory int
AS
DECLARE @i int
DECLARE @numRows int
DECLARE @ShotID int
DECLARE @TagID int
DECLARE @TagName nvarchar(50)
DECLARE @shot_table TABLE(
idx smallint Primary Key IDENTITY(1,1),
ShotID int )
DECLARE @tagID_table TABLE(
idTag smallint Primary Key IDENTITY(1,1),
TagID int)
DECLARE @tagname_table TABLE(
idTagName smallint Primary Key IDENTITY(1,1),
TagName nvarchar(50))
//get all shots in the film
INSERT @shot_table
SELECT Shot.ShotID
FROM Shot
WHERE Shot.FilmID = @filmID
//enumerate through shot table and build a tagID table of all TagIDs associated with any shot found in the shot_table
SET @i = 1
SET @numRows = (SELECT COUNT(*) FROM @shot_table)
IF @numRows > 0
BEGIN
WHILE (@i <= (SELECT MAX(idx) FROM @shot_table))
BEGIN
SET @ShotID = (SELECT ShotID FROM @shot_table WHERE idx = @i)
SET @TagID = (SELECT TaggedShot.TagID FROM TaggedShot WHERE TaggedShot.ShotID = @ShotID)
INSERT INTO @tagID_table(TagID)
VALUES(@TagID)
SET @i = @i + 1
END
END
//compare each TagID found in tagID_table with the TagID in the TaggedCategory table
// insert Tag.Name into new table if the Tag.TagID matches the TagID in the tagID_table and also matches the given tagCategory
SET @i = 1
SET @numRows = (SELECT COUNT(*) FROM @tagID_table)
IF @numRows > 0
WHILE (@i <= (SELECT MAX(idTag) FROM @tagID_table))
BEGIN
SET @TagID = (SELECT TagID FROM @tagID_table WHERE idTag = @i)
IF EXISTS(SELECT TaggedCategory.TagId FROM TaggedCategory WHERE TaggedCategory.CategoryID = @tagCategory)
BEGIN
SET @TagName = (SELECT Tag.Name FROM Tag WHERE Tag.TagId = @TagID)
INSERT INTO @tagname_table(TagName)
VALUES(@TagName)
END
END
//return all the found tag names
SELECT TagName
FROM @tagname_table
这是我想要实现的目标: 鉴于FilmID和标签类别ID(它只是1,2或3的整数 - 我在代码隐藏中确定了这一点),我需要找到给定这两个标准的所有Tag.Names。电影由镜头组成。
答案 0 :(得分:0)
这未经过测试,但您无法通过所提供的表格的简单连接来处理您要实现的目标。如下所示:
SELECT DISTINCT t.NAME
FROM Shot s
INNER JOIN TaggedShot ts ON s.ShotId = ts.ShotId
INNER JOIN Tag t ON ts.TagId = t.TagId
INNER JOIN TaggedCategory tc ON t.TagId = tc.TagId
WHERE s.FilmId = @filmId
AND tc.Categoryid = @tagCategory
根据以下评论进行更新:
SELECT t.TagId
,t.Name
FROM Tag t
WHERE t.TagId IN (
SELECT DISTINCT t.TagId
FROM Shot s
INNER JOIN TaggedShot ts ON s.ShotId = ts.ShotId
INNER JOIN Tag t ON ts.TagId = t.TagId
INNER JOIN TaggedCategory tc ON t.TagId = tc.TagId
WHERE s.FilmId = @filmId
AND tc.Categoryid = @tagCategory)