时间:2021-07-01 10:21:17 帮助过:31人阅读
例1:MariaDB [m33student]> create table student (id tinyint unsigned primary key, name varchar(20) not null, age tinyint unsigned,sex char(1) default "m" );
MariaDB [m33student]> desc student;
+-------+---------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------------+------+-----+---------+-------+
| id | tinyint(3) unsigned | NO | PRI | NULL | |
| name | varchar(20) | NO | | NULL | |
| age | tinyint(3) unsigned | YES | | NULL | |
| sex | char(1) | YES | | m | |
+-------+---------------------+------+-----+---------+-------+
上例演示了建表过程,()内定义了各字段及属性。
若删除刚创建的表student:MariaDB [m33student]> drop table student;
*查看索引(索引的存在极大优化了数据库查询速度,但当新数据插入时,索引降低了插入速度)
MariaDB [m33student]> show indexes from student\G;(\G选项调整了输出效果)
*增加唯一性约束条件
MariaDB [m33student]> alter table student add unique key (phone);
*删除列
MariaDB [m33student]> alter table student drop phone;
*创建索引
MariaDB [m33student]> create index age_index on student(phone);
例2:MariaDB [m33student]> insert into student (id,name,sex) values (4,‘Sarah‘,‘f‘),(5,‘Mily‘,‘f‘),(6,‘Jack‘,default);
上例演示了同时插入多行的情况。
例3:MariaDB [m33student]> delete from emp where id=1;
MariaDB [m33student]> delete from emp;
上例演示了删除表中单行记录以及所有记录。
例4:MariaDB [m33student]> update student set phone=‘18438613802‘ where id=2;
MariaDB [m33student]> update emp set phone=‘18438613802‘ ;
上例演示了针对某一行记录的某个字段的改动,以及对整个表“phone”字段的改动。
注意,对于查询操作而言,由于其可能会涉及到多表联查,函数等功能,因此sql语句会复杂一些。
**查询当前登录的账户:
MariaDB [hellodb]> select user();
**查询当前数据库的版本信息:
MariaDB [hellodb]> select version();
**查询当前使用的数据库:
MariaDB [hellodb]> select database();
例5:MariaDB [hellodb]> select count(*) from scores where score > 50;
MariaDB [hellodb]> select count(distinct classid) from students;
上例中出现了count函数,count() 返回表中满足where条件的行的数量,如没有Where条件,列出所有行的总数。第二行中count函数中又套用了distinct函数,旨在去除重复值。
**最大值,最小值,平均值,求和函数的应用分别为:
select max(score) /min(score)/avg(score)/sum(score) from scores;
算平均值时,注意null不会参与组函数,所以要先用ifnull将null转为0:MariaDB [hellodb]> select avg(ifnull(score,0)) from scores;
例6:select courseid,avg(nullif(score,0)) as avg from scores group by courseid having avg>60;
上例中as avg 作为avg(nullif(score,0))的别名设置,可以省略as,执行后将以courseid为分组只显示均值大于的行,字段为courseid,avg。
**取前6行;取第7,8,9行
select * from students limit 6;
select * from students limit 6,3;
**以年龄排序后,显示年龄最大的前10位同学的信息
MariaDB [hellodb]> select * from students order by age desc limit 10;
运维基本功之mariadb基本操作
标签:ima sid show nullif update char add des 示例