简体   繁体   中英

SQL: Assigning sequence numbers

I would like to assign a sequence number as I add a group of rows to a table. How do I do this? I thought about using COUNT() or ROWID but I cannot figure out how.

Let's say I have a table with three columns: PlayListID, TuneID and SequenceNum

I want to create a new tune playlist, so I'm going to add a bunch of TuneID values for a PlayListID of 2 for example. The TuneIDs are ordered by artist, album and track number. Here's what I have at present:

SELECT TuneID From Tunes
WHERE ArtistID=2
ORDER BY AlbumID, TrackNum

I guess what I am trying to do is preserve the ordering information - ensure that when all tunes for PlayListID=2 are retrieved, they have a column that indicates their order. TrackNum cannot be used as their may be a number of albums and I may write another query to retrieve them in some other order as well.

So, how would I modify the below command to add an ascending column (sequence) value for each row inserted?

INSERT INTO Playlist (Name,Seq)
SELECT Name, ??? As Seq FROM Tunes
WHERE ArtistID=2
ORDER BY AlbumID, TrackNum

I'm using SQLite. I don't want to use autoincrement because I'd like the Seq number to be 1 for each PlaylistID.

try thiz:在播放列表中插入INSERT(名称,序列)从调谐中选择名称,行编号,WHERE ArtistID = 2 ORDER BY AlbumID,TrackNum;

The SQL genius at work solved my problem. Here's the solution - creating a temporary table which has an auto incrementing column..

CREATE TEMP TABLE New_Playlist (Seq INTEGER PRIMARY KEY AUTOINCREMENT, TuneID INTEGER);

INSERT INTO New_Playlist (TuneID)
SELECT TuneID FROM Tunes
WHERE ArtistID=2
ORDER BY AlbumID, Track;

INSERT INTO Playlist (TuneID, Name, Seq)
SELECT t.TuneID, t.Name, np.Seq
FROM New_Playlist np JOIN Tunes t ON t.TuneID = np.TuneID;

DROP TABLE New_Playlist;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM