MySQL基本使用查询

1、简介:查询的基本语法:select * from 表名;

2、消除重复行:select   distinct   字段名    from   表名;

3、条件筛选:select   *  from   表名    where   条件;

4、 比较运算符: =(等于)、>(大于)、<(小于)、>=(大于等于)、<=(小于等于)、!=/<>(不等于)

5、逻辑运算符:and、or、not

6、模糊查询:like 、%表示任意多个任意字符、_表示一个任意字符。

7、范围查询:(1)in表示在一个非连续的范围内: 查询编号是1或3或8的学生=select * from students where id in(1,3,8);

(2)between ... and ...表示在一个连续的范围内: 查询学生是3至8的学生=select * from students where id between 3 and 8;

8、空判断:判断 is null: * 查询没有填写地址的学生=select * from students where hometown is null;

9、优先级:小括号,not,比较运算符,逻辑运算符;

10、聚合函数:min()、max()、sum()、avg()、count();

例题:(1) 查询学生总数:select count(*) from students;(2) 查询女生的编号最大值=select max(id) from students where gender=0;(3)  查询未删除的学生最小编号 = select min(id) from students where isdelete=0;(4) 查询男生的编号之后 = select sum(id) from students where gender=1;(5) 查询未删除女生的编号平均值 = select avg(id) from students where isdelete=0 and gender=0;

11、分组:  按照字段分组,表示此字段相同的数据会被放到一个组中;语法:select 列1,列2,聚合... from 表名 group by 列1,列2,列3...;例题:查询男女生总数:select gender as 性别,count(*) from students group by gender;

对比where与having: where是对from后面指定的表进行数据筛选,属于对原始数据的筛选

having是对group by的结果进行筛选.。

12、排序:语法:select * from 表名 order by 列1 asc|desc,列2 asc|desc,...;默认按照列值从小到大排列,asc从小到大排列,即升序,desc从大到小排序,即降序。

例题:1、查询未删除男生学生信息,按学号降序:select * from students   where gender=1 and isdelete=0 order by id desc;2、查询未删除科目信息,按名称升序:select * from subject where isdelete=0  order by stitle;

13、外键:如果一张表中有一个非主键的字段指向了别一张表中的主键,就将该字段叫做外键。外键的默认作用有两点:1.对子表(外键所在的表)的作用:子表在进行写操作的时候,如果外键字段在父表中找不到对应的匹配,操作就会失败。2.对父表的作用:对父表的主键字段进行删和改时,如果对应的主键在子表中被引用,操作就会失败。

14、使用外键的前提:1. 表储存引擎必须是innodb,否则创建的外键无约束效果。

2. 外键的列类型必须与父表的主键类型完全一致。

3. 外键的名字不能重复。

4. 已经存在数据的字段被设为外键时,必须保证字段中的数据与父表的主键数据对应起来

导入sql文件命令mysql>use database;

mysql>source d:/mysql.sql;

猜你喜欢

转载自blog.csdn.net/weixin_33973600/article/details/87641561