操作表记录
问题
练习表记录的操作
1)表记录的插入
2)表记录的更新
3)表记录的查询
4)表记录的删除
步骤
实现此案例需要按照如下步骤进行。
步骤一:删除上次试验stu_info表中记录
删除stu_info表的所有记录:
mysql> DELETE FROM stu_info;
Query OK, 3 rows affected (0.00 sec)
确认删除结果:
mysql> SELECT * FROM stu_info;
Empty set (0.00 sec)
步骤二:练习表记录的操作
1)插入记录时,指定记录的每一个字段的值
这种情况下,不需要明确指出字段,但每条记录的值的顺序、类型都必须与表格结构向一致,否则可能无法正确插入记录。
比如,以下操作将向stu_info表插入3条表记录:
mysql> INSERT stu_info VALUES
-> ('Jim','girl',24),
-> ('Tom','boy',21),
-> ('Lily','girl',20);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
完成插入后确认表记录:
mysql> SELECT * FROM stu_info;
+------+--------+-----+
| name | gender | age |
+------+--------+-----+
| Jim | girl | 24 |
| Tom | boy | 21 |
| Lily | girl | 20 |
+------+--------+-----+
3 rows in set (0.00 sec)
2)插入记录时,只指定记录的部分字段的值
这种情况下,必须指出各项值所对应的字段;而且,未赋值的字段应设置有默认值或者有自增填充属性或者允许为空,否则插入操作将会失败。
比如,向stu_info表插入Jerry的年龄信息,性别为默认的“boy”,自动编号,相关操作如下:
mysql> INSERT INTO stu_info(name,age)
-> VALUES('Jerry',27);
Query OK, 1 row affected (0.00 sec)
类似的,再插入用户Mike的年龄信息:
mysql> INSERT INTO stu_info(name,age)
-> VALUES('Mike',21);
Query OK, 1 row affected (0.00 sec)
确认目前stu_info表的所有记录:
mysql> SELECT * FROM stu_info;
+-------+--------+-----+
| name | gender | age |
+-------+--------+-----+
| Jim | girl | 24 |
| Tom | boy | 21 |
| Lily | girl | 20 |
| Jerry | boy | 27 |
| Mike | boy | 21 |
+-------+--------+-----+
5 rows in set (0.00 sec)
3)更新表记录时,若未限制条件,则适用于所有记录
将stu_info表中所有记录的age设置为10:
mysql> UPDATE stu_info SET age=10;
Query OK, 5 rows affected (0.00 sec)
Rows matched: 5 Changed: 5 Warnings: 0
确认更新结果:
mysql> SELECT * FROM stu_info;
+-------+--------+-----+
| name | gender | age |
+-------+--------+-----+
| Jim | girl | 10 |
| Tom | boy | 10 |
| Lily | girl | 10 |
| Jerry | boy | 10 |
| Mike | boy | 10 |
+-------+--------+-----+
5 rows in set (0.00 sec)
4)更新表记录时,可以限制条件,只对符合条件的记录有效
将stu_info表中所有性别为“boy”的记录的age设置为20:
mysql> UPDATE stu_info SET age=20
-> WHERE gender='boy';
Query OK, 3 rows affected (0.01 sec)
Rows matched: 3 Changed: 3 Warnings: 0
确认更新结果:
mysql> SELECT * FROM stu_info;
+-------+--------+-----+
| name | gender | age |
+-------+--------+-----+
| Jim | girl | 10 |
| Tom | boy | 20 |
| Lily | girl | 10 |
| Jerry | boy | 20 |
| Mike | boy | 20 |
+-------+--------+-----+
5 rows in set (0.00 sec)
5)删除表记录时,可以限制条件,只删除符合条件的记录
删除stu_info表中年龄小于18的记录:
mysql> DELETE FROM stu_info WHERE age < 18;
Query OK, 2 rows affected (0.04 sec)
确认删除结果:
mysql> SELECT * FROM stu_info;
+-------+--------+-----+
| name | gender | age |
+-------+--------+-----+
| Tom | boy | 20 |
| Jerry | boy | 20 |
| Mike | boy | 20 |
+-------+--------+-----+
3 rows in set (0.00 sec)
6)删除表记录时,如果未限制条件,则会删除所有的表记录
删除stu_info表的所有记录:
mysql> DELETE FROM stu_info;
Query OK, 3 rows affected (0.00 sec)
确认删除结果:
mysql> SELECT * FROM stu_info;
Empty set (0.00 sec)