MySql数据库之单表数据查询

查询数据

1.查询所有数据:

select * from 表名;

2.根据指定条件查询数据:

select * from 表名 where 查询条件

3.根据where条件查询:

  3.1 根据指定条件查询指定字段的数据

select 字段1,... from 表名 where 查询条件

   这里为大家简述一下这条命令执行的基本流程:

    1.先执行from命令,从指定表中取出数据;

    2.在通过查询条件,将符合条件的数据筛选出来;

    3.最后,再查询出指定字段包含的数据并显示出来。

  3.2 where结合逻辑运行算符进行查询

  首先,我们需要先明确一下逻辑运算符都包括什么:

    and:与运算;

-- where结合and使用
select * from 表名 where 查询条件1 and 查询条件2;

当两个查询条件都满足时才能够查询出数据。

    or:或运算;

-- where 结合 or 
select * from 表名 where 查询条件1 or 查询条件2;

当两个查询条件中有一个满足时就会查询出数据。

    not:取反。

--where 结合 not
select * from 表名 where not (查询条件);

当满足与查询条件相反时查询出数据。

注意:not的运算符优先级比and 和 or 大;not>and>or。

  3.3 模糊查询

利用通配符进行模糊查询。

模糊查询的通配符有:

  1.%:匹配任意个字符;

  2._:匹配任意一个字符。

-- 模糊查询
select * from t_student where name='王%';
-- 表示查询出所有姓王的学生的信息

select * from t_student where name='王_';
-- 表示查询出所有姓王、名字为两个字的学生的信息

  3.4 范围查询

范围查询的关键字有:

  1.between ... and ..

  2.in(数据1,...)

--between ... and 使用
select name.age from t_student where age between 18 and 20;
-- 表示查询出年龄在18到20之间的学生姓名和年龄(包括18和20)

-- in 使用
select s_id,name from t_student where s_id in(16280101,16280202,16280333);
-- 表示查询出学号在这个范围(16280101,16280202,16280333)内的学生的学号和姓名

  3.5 空判断查询

关键字:

  1.is null :空

  2.is not null :非空

-- is null 使用
select * from t_student where phone is null;
-- 表示查询出所有电话号为空的学生信息

--is not null使用
select * from t_student where phone is not null;
-- 表示查询出所有电话号非空的学生信息

注意:

is not null 和not is null查询出来的数据是一样的但是原理不同;

is not nul 是 直接判断字段内的数据是否为非空;

not is null 是 先判断字段内的数据是否为空,然后再进行取反操作,效率较低。

  3.6 数据排序

使用关键字order by desc/asc对查询出的数据进行排序。

-- order by desc
select * from 表名 where 查询条件 order by desc
-- 表示先查询出指定数据在进行降序排列

-- order by asc
select * from 表名 where 查询条件 order by asc;
-- 表示先查询出指定数据再进行升序排列

  3.7 分页查询

使用关键字limit进行分页查询

-- limit 使用
select * from t_student where phone is not null limit 0,10;
--表示查询出10条电话非空的学生的信息

--分页查询计算公式
limit (page-1)*count,count;

  3.8 分组查询

使用group by关键字进行分组。

-- 无分组条件查询
select adress,group_concat(name) from t_student group by address;
-- 表示使用address分组,并查询出分组信息以及每组内的学生姓名

-- 有分组条件查询
select address,group_concat(name) from t_student group by address having count(name)<3;
-- 表示使用address分组,并显示出人数小于3人的小组信息以及组内的学生姓名

猜你喜欢

转载自www.cnblogs.com/chao666/p/12033870.html