MariaDB(selec的使用)
阅读原文时间:2023年07月08日阅读:1

--查询基本使用

-- 查询所有列

--select * from 表名

select * from students;

--一定条件查询

select * from students where name='小李飞刀';

select * from students where id>3;

-- 查询制定列

select name, gender from students;

-- 可以使用as制定列或表制定别名;

select name as 姓名, gender as 性别 from students;

--字段的顺序

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

--创建学生表

create table students (

id int unsigned not null auto_increment primary key,

name varchar(20) default '',

age tinyint unsigned default 0,

high decimal(5,2),

gender enum('男', '女', '中性', '保密') default '保密',

cls_id int unsigned default 0,

is_delete bit default 0

);

--创建班级表

create table classes(

id int unsigned auto_increment primary key not null,

name varchar(20) not null

);

--往students表里插入数据

insert into students values

(0,'小明',18,180.00,2,1,0),

(0,'小月月',19,180.00,2,2,0),

(0,'布莱恩特',28,185.00,1,1,0),

(0,'刘德华',58,175.00,1,2,0),

(0,'黄蓉',108,160.00,2,1,0),

(0,'凤姐',44,150.00,4,2,1),

(0,'李白',52,170.00,2,1,1),

(0,'周杰伦儿',34,null,1,1,0),

(0,'程坤',44,181.00,1,2,0),

(0,'金镖十三郎',55,166.00,2,2,0),

(0,'刘亦菲',29,162.00,3,3,0),

(0,'金星',45,180.00,2,4,0),

(0,'静香',18,170.00,1,4,0),

(0,'项羽',22,167.00,2,5,0),

(0,'周杰',33,178.00,1,1,0);

--向classes表里插入数据

insert into classes values (0, 'python_01期'),(0, 'python_02期');

-- 查询所有字段

select * from students;

select * from classes;

-- 查询制定的字段

select name, age from students;

-- 使用as给字段起别名

select name as 姓名, age as 年龄 from students;

-- 通过表名字查询

select students.name, students.age from students;

-- 给表起别名查询

select s.name, s.age from students as s;

--消除重复行

-- distinct

select distinct gender from students;

--比较运算符

-- 查询年纪大于18岁的信息

select * from students where age > 18;

select id, name, gender from students where age > 18;

--18岁到28岁之间(and)

select * from students where age>18 and age<28;

--在18岁以上或者身高180以上的人(or)

select * from students where age>18 or high>=180;

-- like

-- % 替代1个或者多个甚至是没有

select * from students where name like '小%';

-- 查询姓名中有‘小’的所有名字

select * from students where name like '%小%';

-- 查询有两个字的名字

select * from students where name like '__';

-- 查询至少有2个字的名字

select * from students where name like '__%';

-- 查询以周开始的名字

select * from students where name rlike '^周.*';

select * from students where name rlike '^周.*儿$';

-- in (1,3,8)表示在一个非连续的范围内

-- 查询 年纪为18,34的人

select * from students where age=18 or age=34;

select * from students where age=18 or age=34 or age=12;

select * from students where age in (12,18,34);

--查询 年龄在17岁到34岁之间的信息

select * from students where age between 18 and 34;--(不包含34岁)

--查询 年纪不在18到34岁的信息

select * from students where age not between 18 and 34;

-- 判断is null

-- 查询身高为空的信息

select * from students where high is null;

-- 判断非空is not null

select * from students where high is not null;

select * from students order by age asc;   

  asc从小到大排序

 desc从小到大