MySQL
 Computer >> コンピューター >  >> プログラミング >> MySQL

MySQLで1つの行を削除し、他の行を正しいIDで並べ替えますか?


概念を理解するために、最初にテーブルを作成しましょう。テーブルを作成するためのクエリは次のとおりです

mysql> create table ReorderSortDemo
   -> (
   -> UserId int
   -> );
Query OK, 0 rows affected (0.57 sec)

挿入コマンドを使用して、テーブルにいくつかのレコードを挿入します。クエリは次のとおりです-

mysql> insert into ReorderSortDemo values(14);
Query OK, 1 row affected (0.13 sec)
mysql> insert into ReorderSortDemo values(4);
Query OK, 1 row affected (0.10 sec)
mysql> insert into ReorderSortDemo values(6);
Query OK, 1 row affected (0.11 sec)
mysql> insert into ReorderSortDemo values(3);
Query OK, 1 row affected (0.09 sec)
mysql> insert into ReorderSortDemo values(8);
Query OK, 1 row affected (0.11 sec)
mysql> insert into ReorderSortDemo values(18);
Query OK, 1 row affected (0.08 sec)
mysql> insert into ReorderSortDemo values(1);
Query OK, 1 row affected (0.12 sec)
mysql> insert into ReorderSortDemo values(11);
Query OK, 1 row affected (0.08 sec)
mysql> insert into ReorderSortDemo values(16);
Query OK, 1 row affected (0.09 sec)

selectステートメントを使用して、テーブルのすべてのレコードを表示します。クエリは次のとおりです-

mysql> select *from ReorderSortDemo;

以下は出力です

+--------+
| UserId |
+--------+
|     14 |
|      4 |
|      6 |
|      3 |
|      8 |
|     18 |
|      1 |
|     11 |
|     16 |
+--------+
9 rows in set (0.00 sec)

最初にテーブルから1つの行を削除してから、updateコマンドを使用して他の行を並べ替えます。クエリは次のとおりです-

mysql> delete from ReorderSortDemo where UserId=8;
Query OK, 1 row affected (0.20 sec)

削除後、もう一度テーブルレコードを確認してみましょう。クエリは次のとおりです-

mysql> select *from ReorderSortDemo;

出力は次のとおりです

+--------+
| UserId |
+--------+
|     14 |
|      4 |
|      6 |
|      3 |
|     18 |
|      1 |
|     11 |
|     16 |
+--------+
8 rows in set (0.00 sec)

他の列を並べ替えるクエリは次のとおりです

mysql> update ReorderSortDemo
   -> set UserId=UserId-1
   -> where UserId > 8;
Query OK, 4 rows affected (0.22 sec)
Rows matched: 4 Changed: 4 Warnings: 0

テーブルレコードをもう一度確認しましょう。クエリは次のとおりです-

mysql> select *from ReorderSortDemo;

出力は次のとおりです

+--------+
| UserId |
+--------+
|     13 |
|      4 |
|      6 |
|      3 |
|     17 |
|      1 |
|     10 |
|     15 |
+--------+
8 rows in set (0.00 sec)

  1. MySQLで値の1つをキャストし、他の値と除算を実行しますか?

    このためには、最初にCAST()を使用します。まずテーブルを作成しましょう- mysql> create table DemoTable1352     -> (     -> Value1 int,     -> Value2 int     -> ); Query OK, 0 rows affected (0.54 sec) 挿入コマンドを使用してテーブルにいくつかのレコードを挿入します- mysql> insert into DemoTable1352 values(10

  2. 重複を削除してMySQLのテーブルに1行を残す方法は?

    重複を削除してテーブルに1行を残すには、一時テーブルの概念を使用する必要があります。手順は次のとおりです- create table anytemporaryTableName as select distinct yourColumnName1, yourColumnName2 from yourTableName; truncate table yourTableName; insert into yourTableName(yourColumnName1, yourColumnName2) select yourColumnName1, yourColumnName2 from your