I\'m completely new to sql and can\'t do that myself. So I need your help. I want to sort values in column and then save changes. But I don\'t know how to do that.
T
You can use alter table command which is simpler.
mysql> ALTER TABLE games ORDER BY name asc;
That's all !
You would have to use a second table
create a new table games2
with the same structure as your games
table, making sure the ID is auto-incrementing
CREATE TABLE `games2` LIKE `games`;
copy the data, sorted, into games2
INSERT INTO `games2` (`Name`, `SomeDescription`) SELECT `Name`, `SomeDescription` FROM `games` ORDER BY `Name`
drop or move the old table
-- DROP TABLE `games`;
-- or
RENAME TABLE `games` TO `games1`;
rename new table to old name
RENAME TABLE `games2` TO `games`;
These steps will result in what you want.
you can sort on two fields at the same time.
SELECT *
FROM games
ORDER BY id DESC, name ASC
I don't understand what you mean by save changes in the table. The ORDER BY
, is just changing the display that you are looking at it doesn't change the data in the table unless you perform an UPDATE
.
If you are unfamiliar with SQL, there are a lot of tutorials online that can help:
SQL Course
Beginner SQL Tutorial
SQL Tutorial - Learn SQL
Edit based on the comments, this can be done in one step:
create table #temp
(
id int,
name varchar(50),
somedesc varchar(50)
)
insert into #temp values (1, 'best', 'desc1')
insert into #temp values (2, 'worth', 'desc2')
insert into #temp values (3, 'good', 'desc3')
update t1
SET t1.id = t2.rn
, t1.somedesc = t1.somedesc
FROM #temp t1
JOIN
(
select id, name, somedesc, row_number() over(order by name, id) as rn
from #temp
) t2
on t1.id = t2.id
select *
from #temp
order by id
drop table #temp
You can use the ROW_NUMBER ranking function to renumber the rows.
SELECT UnsortedId = id
, SortedId = ROW_NUMBER() OVER (ORDER BY g.name, g.id)
FROM games
This is my fix... stupid simple:
SELECT SortKeyValue (add any other fixed values, just don't include the existing sequence) INTO #Temp FROM SourceTable;
TRUNCATE TABLE SourceTable
INSERT INTO SourceTable (SortKeyValue, DisplayOrder (plus other fields)) SELECT SortKeyValue, ROW_NUMBER() OVER (ORDER BY SortKeyValue) AS DispOrd (plus other fields) FROM #Temp;
it is simple. just use a few codes. I have tried this and it is working. first create a temporary table while sorting values at the same time.
create table new as select * from games order by name;
and then drop the games table using,
drop table games;
now create games table again with same properties and data as in new (where sorting here is an optional) using,
create table games as select * from new order by name;
now drop the temp table 'new'
drop table new;
now check your table. it must be sorted out.