MySQL基本操作
目录
- 创建库、表
- 插入数据
- 修改
- 查找
- select
- where
创建库、表
创建学生信息库:
mysql> create database students;
创建学生信息表:
mysql> use students;
mysql> create table if not exists students(
-> id int unsigned primary key auto_increment comment '用户的主键',
-> sn int not null unique comment '学生的学号',
-> name varchar(20) not null,
-> qq varchar(20) unique
-> );
查看结果:
mysql> desc students;
插入数据
单行数据 + 全列插入:
mysql> insert into students values(100,10000,'蔡徐坤',NULL);
mysql> insert into students values(101,10001,'陈立农',NULL);
多行数据 + 指定列插入:
mysql> insert into students (id,sn,name) values
-> (102,20001,'范丞丞'),
-> (103,20002,'黄明昊'),
-> (104,20003,'林彦俊'),
-> (105,20004,'朱正廷');
查看插入结果:
mysql> select * from students;
修改
目前的qq是NULL,可以修改:
mysql> update students set qq = '11111' where name = '蔡徐坤';
mysql> update students set qq = '22222' where name = '陈立农';
mysql> update students set qq = '33333' where name = '范丞丞';
查看结果:
上述直接修改,接下来也可以在插入时检测自动更新
再次插入,检测到数据冲突自动更新(id冲突):
mysql> insert into students (id,sn,name,qq) values (100,10000,'蔡徐坤',11111) on duplicate key update qq='11112';
结果:冲突代表一次affected,修改代表第二次affected:
Query OK, 2 rows affected (0.00 sec)
这种方法常用于不确定该条目是否存在,但是你又想去修改它的数据。作用其实相当于replace
replace的功能是如果没检测到冲突,就直接插入,如果有冲突,就将该行全部删掉,再重新插入。
查找
SQL查询中各个关键字的执行先后顺序 from > on> join > where > group by > with > having > select
distinct > order by > limit
select
一般不使用全部搜索,因为数据可能会过于庞大:
mysql> select * from students;
- 通常使用指定列搜索:
mysql> select id,sn,name from students;
也可以调整顺序:
mysql> select id,name,sn from students;
- 搜索自定义字段,但必须是一个可计算表达式:
mysql> select id,sn+10 from students;
mysql> select id,sn+id from students;
- 给自定义列起别名
mysql> select id,sn+id id加学号 from students;
- 去重
mysql> select distinct xxx from students;
where
- 比较运算符
LIKE:模糊匹配。% 表示任意多个(包括 0 个)任意字符;_ 表示任意一个字符
- 逻辑运算符
- AND----多个条件必须都为 TRUE(1),结果才是 TRUE(1)
- OR----任意一个条件为 TRUE(1), 结果为 TRUE(1)
- NOT----条件为 TRUE(1),结果为 FALSE(0)
where条件是最先查找的,所以别名不可用于where条件中,因为此时的别名还未生成。
因此where条件中必须是表达式
查找id小于103的字段:
mysql> select id,sn from students where id<103;
id = 10x的字段:
mysql> select id from students where id like '10%';
也可以使用’_'来严格匹配某个字段