MySQL命令学习1

    技术2022-07-12  74

    MYSQL学习1

    MySql环境:MySql8.0.19

    1 .使用命令行客户端操作数据库的相关命令

    ①显示所有数据库

    show databases;

    ② 使用某个数据库

    use test;

    ③显示数据库中的所有表

    show tables;

    ④ 显示某表的所有字段信息

    show columns from users;

    2 .检索数据

    ①查询某表的所有数据

    查询users表的全部数据

    select * from users;

    ② 查询某表中的特定字段的数据

    查询users表中username,userage字段的数据,字段名用逗号隔开

    select username,userage from users;

    ③ 使用distinct限制结果

    select distinct userage from users;

    如上表中userage=24有两个 不能部分使用distinct 该关键字应用于所有列而不是前置它的列

    select distinct userage,username from users;

    必须是查询的两个字段的值为相同,才会显示一列

    ④ 使用limit关键字限制数据行数(分页查询)

    显示前两行

    #第一个参数0:表示从第一行开始查询 #第二个参数2:表示显示两行数据 select * from users limit 0,2;

    ⑤ 使用完全限定的表名

    select users.id from test.users;

    3 .排序检索数据

    ①使用order by 子句进行排序检索

    按字典顺序进行排序

    select * from users order by username;

    ② 使用order by 子句给多个列排序

    select * from users order by username,userage;

    ③ 使用desc进行降序排序

    按年龄进行降序排序(默认升序)

    select * from users order by userage desc;

    ④ 对多个列做降序排序

    desc只作用与其前面的列名,如下按年龄降序,如年龄相同,则按用户名升序排序

    select * from users order by userage desc,username;

    如果想要在多个列上进行降序排序,必须为每个列添加desc关键字

    相反的是asc为升序,不过默认就是升序,因此作用不大

    ⑤ 使用order by 与limit关键字查找最大与最小值

    查找年龄最小的用户

    select * from users order by userage limit 0,1;

    查找年龄最大的用户

    select * from users order by userage desc limit 0,1;

    4 .过滤数据

    ①使用where子句获取指定要求的数据

    查询年龄为24的用户

    select * from users where userage=24;

    在同时使用where与order by子句时,order by应位于where子句之后,否则报错

    ② 使用between关键字获取某个范围的值

    查询年龄为20到23之间的值

    select * from users where userage between 20 and 23;

    ③ 空值检查

    使用is null来判断

    没有userage为空值的列

    5 .数据过滤

    ① 使用and操作符来进行查询

    如上述4.②查询中查询20到23的年龄的用户等价操作如下

    select * from users where userage>=20 and userage<=23;

    ② 使用or操作符查询年龄大于等于23或者小于15的用户

    select * from users where userage>=23 or userage<15;

    and操作符的优先级大于or操作符,如果组合使用时,用括号限定才会更好

    ③ 使用and 与 or组合

    例如:查询id=3或id=6的用户且年龄大于等与23

    select * from users where userage>=23 and id=3 or id=6;

    如上图userage>=23 and id=3进行了组合 id=6为单个条件了

    select * from users where userage>=23 and (id=3 or id=6);

    使用括号限定组合查询条件可以明确指定查询条件,否则会出现歧义

    ④ in操作符的使用

    in操作符可以用来指定条件匹配,我们同样使用in查询年龄为20,23,24的用户

    select * from users where userage in(20,23,24);

    使用in操作符的优点:

    在使用长的合法选项清单时,in操作符的语法更清楚更直观

    在使用in时,计算的次序更容易管理

    in操作符一般比or操作符清单执行更快

    in的最大优点是可以包含其他select语句,使得能够更动态地建立where子句

    ⑤ not操作符的使用

    列出除了年龄为20,24的用户

    select * from users where userage not in(20,24);

    6 .使用通配符过滤数据

    使用like操作符

    ① 使用%通配符

    % 表示0个或多个字符

    例如查询用户名为ke开头的用户

    select * from users where username like 'ke%';

    null是不能被%所匹配的

    ② _ 匹配符

    下划线匹配单个字符

    例如查询用户为muke开头的但是为5个字符的用户

    select * from users where username like 'muke_';

    如果用户为muke20则无法匹配

    Processed: 0.011, SQL: 9