在我们介绍两个关键词的用法之前,必要先把数据环境准备好。

创建数据库

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");

查看表中的所有数据
Mysql数据库中的as和distinct的使用

as起别名

as关键字在自连接查询的时候,经常使用,非常重要

1.使用 as 给字段起别名

select id as 序号, name as 名字, gender as 性别 from students;

Mysql数据库中的as和distinct的使用
2.通过 as 给表起别名

表名.字段名

select students.id,students.name,students.gender from students;

可以通过 as 给表起别名

select s.id,s.name,s.gender from students as s;

Mysql数据库中的as和distinct的使用

distinct消除重复行

在查询的时候,当有多条重复数据的时候,使用distinct可以消除重复行

例:查询班级中学生的性别

select distinct gender from students;

Mysql数据库中的as和distinct的使用
总结下:

  1. as 关键字可以给表中字段 或者 表名起别名
  2. distinct 关键字可以把数据去重distinct 关键字可以把数据去重

相关文章:

  • 2021-09-13
  • 2022-12-23
  • 2021-06-21
  • 2022-01-03
  • 2021-08-26
  • 2021-11-02
猜你喜欢
  • 2021-11-17
  • 2021-08-16
  • 2021-12-14
  • 2021-08-16
  • 2021-08-16
  • 2021-08-16
  • 2021-11-29
相关资源
相似解决方案