MySQL的基本使用(2)

一. 基本查询语句

 示例:

创建数据库、数据表

准备数据

-- 创建数据库
create database python_test_1 charset=utf8;

-- 使用数据库
use python_test_1;

-- students表
create table students(
    id int unsigned primary key auto_increment not null,
    name varchar(20) default '',
    age tinyint unsigned default 0,
    height decimal(5,2),
    gender enum('','','中性','保密') default '保密',
    cls_id int unsigned default 0,
    is_delete bit default 0
);

-- classes表
create table classes (
    id int unsigned auto_increment primary key not null,
    name varchar(30) not null
);
-- 向students表中插入数据
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'刘德华',59,175.00,1,2,1),
(0,'黄蓉',38,160.00,2,1,0),
(0,'凤姐',28,150.00,4,2,1),
(0,'王祖贤',18,172.00,2,1,1),
(0,'周杰伦',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'刘亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'静香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0);

-- 向classes表中插入数据
insert into classes values (0, "python_01期"), (0, "python_02期");

 基本语句:

  1. 查询所有字段
  2. 查询指定字段
  3. 使用 as 给字段起别名
  4. 可以通过 as 给表起别名
  5. 消除重复行distinct

查询所有字段 查询指定字段 使用 as 给字段起别名 可以通过 as 给表起别名
select * from 表名;
例:
select * from students;
select 列1,列2,... from 表名;
例:
select name from students;
select id as 序号, name as 名字, gender as 性别 from students;
-- 如果是单表查询 可以省略表明
select id, name, gender from students;

-- 表名.字段名
select students.id,students.name,students.gender from students;

-- 可以通过 as 给表起别名 
select s.id,s.name,s.gender from students as s;

 

二. 分页查询 

1. 分页查询的介绍

当我们在京东购物,浏览商品列表的时候,由于数据特别多,一页显示不完,一页一页的进行显示,这就是分页查询

2. 分页查询的语法

select * from 表名 limit start,count

说明:

  1. limit是分页查询关键字
  2. start表示开始行索引,默认是0
  3. count表示查询条数
例1:查询前3行男生信息:  例2: 已知每页显示m条数据,求第n页显示的数据

提示: 关键是求每页的开始行索引

查询学生表,获取第n页数据的SQL语句:

select * from students where gender=1 limit 0,3;
简写
select * from students where gender=1 limit 3;
select * from students limit (n-1)*m,m

3. as和distinct关键字

3.1 as关键字

在使用SQL语句显示结果的时候,往往在屏幕显示的字段名并不具备良好的可读性,此时可以使用 as 给字段起一个别名。

使用 as 给字段起别名 可以通过 as 给表起别名
select id as 序号, name as 名字, gender as 性别 from students;
-- 如果是单表查询 可以省略表名
select id, name, gender from students;

-- 表名.字段名
select students.id,students.name,students.gender from students;

-- 可以通过 as 给表起别名 
select s.id,s.name,s.gender from students as s;

说明:

  • 在这里给表起别名看起来并没有什么意义,然而并不是这样的,在后期学习 自连接 的时候,必须要对表起别名。

 

3.2  distinct关键字

distinct可以去除重复数据行。

select distinct 列1,... from 表名;

例: 查询班级中学生的性别
select name, gender from students;

-- 看到了很多重复数据 想要对其中重复数据行进行去重操作可以使用 distinct
select distinct name, gender from students;
原文地址:https://www.cnblogs.com/zeon/p/13584811.html