我一直试图让这个工作一段时间,所以有时间问。我正在使用SQL Server CE 4.0,下面的SQL语句返回记录,但我正在尝试再添加一个记录。
在ShowSongRef
表格中,有SongOrder
列。我只想返回歌曲有序的节目。
换句话说,对于下面的SongID硬编码,他们需要SongOrder
1和2或4和5,任何组合,只要它是有序的,一首歌就在另一首之后播放它可能是一组歌曲(超过两首)。
SELECT sh.ID
FROM Songs s
INNER JOIN ShowSongRef ref ON ref.SongID = s.ID
INNER JOIN Shows sh ON sh.ID = ref.ShowID
WHERE ref.SongID IN ('654', '321')
--ORDER BY sh.ID, ref.SongOrder
所有需要的是sh.ID所以我一直在尝试GROUP BY而没有运气。 任何意见都表示赞赏。
谢谢!
编辑:
这是一些实际运行和测试的SQL
以下建议选择无效。
DECLARE @Shows TABLE (ID INT)
INSERT INTO @Shows (ID) VALUES (1)
INSERT INTO @Shows (ID) VALUES (1546)
DECLARE @Songs TABLE (ID INT, Name VARCHAR(256))
INSERT INTO @Songs (ID, Name) VALUES (1, 'Song 1')
INSERT INTO @Songs (ID, Name) VALUES (2, 'Song 2')
INSERT INTO @Songs (ID, Name) VALUES (3, 'Song 3')
INSERT INTO @Songs (ID, Name) VALUES (654, 'Song 4')
INSERT INTO @Songs (ID, Name) VALUES (321, 'Song 5')
DECLARE @ShowSongRef TABLE (ID INT, ShowID INT, SongID INT, SongOrder INT)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (1, 1, 1, 1)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (2, 1, 2, 2)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (3, 1, 321, 3)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (4, 1, 3, 4)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (5, 1546, 3, 1)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (6, 1546, 1, 2)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (7, 1546, 654, 3)
INSERT INTO @ShowSongRef (ID, ShowID, SongID, SongOrder) VALUES (8, 1546, 321, 4)
SELECT sh.ID
FROM @Songs s
INNER JOIN @ShowSongRef ref ON ref.SongID = s.ID
INNER JOIN @ShowSongRef ref2 ON ref2.SongID = s.ID
AND Ref2.SongOrder = Ref.SongOrder + 1
AND ref.ShowID = ref2.ShowID
INNER JOIN @Shows sh ON sh.ID = ref.ShowID
WHERE ref.SongID IN ('654', '321')
答案 0 :(得分:0)
向ShowSongRef添加第二个连接,以确保在所需顺序中的第一首歌之后有第二首歌曲。
所以下面会:
因此,只有在同一个节目中按顺序排列的歌曲才能返回。但是只有配对的第一首作为第二首歌Doens没有随后的歌曲;但是这两首歌都可用,因为你有ref和ref2可以使用。
--SELECT sh.ID, s.Name, ref.SongOrder FROM Songs s
SELECT sh.ID FROM Songs s
INNER JOIN ShowSongRef ref
ON ref.SongID = s.ID
INNER JOIN ShowSongRef ref2
ON ref2.SongID = s.SongID - ok we need to make sure the song is fk to songs
and Ref2.SongOrder = Ref.SongOrder+1 --this is the trick (assumes song order is numeric)
and ref.ShowID = ref2.ShowID -- we only want to consider songs in the same show
INNER JOIN Shows sh
ON sh.ID = ref.ShowID
WHERE ref.SongID IN ('654', '321')
- ORDER BY sh.ID,ref.SongOrder