Mysql
最有效的訂貨後數據庫設計
我有包含 post_order 列的文章表。我將每個文章的順序儲存在其中。當我將一行的順序從 25 更改為 15 時,我應該將所有行從 15 更新到結尾。這對幾行有好處,但在數千行中是最差的。
有沒有更好的排序文章設計,更高效?
您可以將
post_order
列更改為 a並使用您想要結束的文章float
中的值通過計算更新值。post_order
例子:
PostID, PostOrder 1 1 2 2 3 3
如果您想移動 PostID = 3 以在 1 和 2 之間排序,它將是
PostID, PostOrder 1 1 3 1.5 2 2
這是一個 SQL Fiddle,其中包含一些使用儲存過程移動文章的程式碼,在該儲存過程中,您傳入
PostID
要移動PostID
的文章和您想要結束的文章。MySQL 5.5.30 架構設置:
create table Post ( PostID int primary key, PostOrder float unsigned not null unique, check (PostOrder > 0) ); insert into Post(PostID, PostOrder) values (1, 1); insert into Post(PostID, PostOrder) values (2, 2); insert into Post(PostID, PostOrder) values (3, 3); insert into Post(PostID, PostOrder) values (4, 4); insert into Post(PostID, PostOrder) values (5, 5); insert into Post(PostID, PostOrder) values (6, 6); insert into Post(PostID, PostOrder) values (7, 7); insert into Post(PostID, PostOrder) values (8, 8); insert into Post(PostID, PostOrder) values (9, 9); insert into Post(PostID, PostOrder) values (10, 10); // create procedure MovePost(MovePostID int, AfterPostID int) begin declare AfterPostOrder float; declare NextPostOrder float; set AfterPostOrder = (select PostOrder from Post where PostID = AfterPostID); if AfterPostOrder is null then -- Move first set AfterPostOrder = 0; end if; set NextPostOrder = (select min(PostOrder) from Post where PostOrder > AfterPostOrder); if NextPostOrder is null then -- Move last set NextPostOrder = (select max(PostOrder) + 2 from Post); end if; update Post set PostOrder = (AfterPostOrder + NextPostOrder) / 2 where PostID = MovePostID; end
查詢 1:
call MovePost (7, 3); -- Move 7 after 3 call MovePost (8, 3); -- Move 8 after 3 call MovePost (9, null); -- Move 9 first call MovePost (2, 10); -- Move 2 after 10 select * from Post order by PostOrder
結果:
| POSTID | POSTORDER | ---------------------- | 9 | 0.5 | | 1 | 1 | | 3 | 3 | | 8 | 3.25 | | 7 | 3.5 | | 4 | 4 | | 5 | 5 | | 6 | 6 | | 10 | 10 | | 2 | 11 |