简单常用的sql语句
以常见数据库管理工具(DBMS)mysql为例介绍一些常见的sql语句:
mysql成功安装后命令行登陆mysql命令:mysql -u root -p
创建一个名为my_database的数据库:
create database my_database;
// 查看DBMS存在的数据库:
show databases;
// 可查看到自己创建的数据库以及四个系统默认存在的数据库
// 显示的数据库中你需选择一个你想要使用的数据库,才可以查看和操作该数据库:
use my_database;
// 也可以在查询和操作表时再指明数据库,只是该用法为一次性的,它并没有选择任何数据库
select user.User from mysql.user; // mysql.user即mysql数据库的user表
// 查看数据库中存在的全部表
show tables;
// 创建表
// cust_id 项设置为 int ,非空 , 主键 , 自增
create table customers(
cust_id int not null primary key auto_increment,
cust_name char(50) not null
);
// 查看表的全部列 ( 二选一 )
describe 表名;
select colums from 表名;
// 删除表
drop table 表名;
// 给表插入数据
insert into 表名(列1,列2) values (数据1, 数据2);
demo: insert into customers(cust_name, cust_id) values ('jeff', 1);
// 给数据表的某一列设置主键(注:每一个数据表只能有一个主键)
alter table 表名 add primary key(列名);
demo: alter table customers add primary key(cust_id);
// 给表增加一个列
alter table 表名 add 列名 char(50);
demo: alter table customers add cust_desc char(50);
// 该命令会报错,因为desc是关键字。小心使用到关键字。
// 删除表的一个列
alter table 表名 drop column cust_desc;
// 查看表中全部列对应的值
select * from customers;
// 表中没有数据则返回 empty set (0.00)
// DISTINCT关键字
select DiSTINCT cust_name from customers;
// 挑选出不重复的列名为user的数据
// limit关键字
select cust_name from customers limit 3; // 限制三条数据
select cust_name from customers limit 0,2 // 从第一行开始寻找,限制两条数据;初始化为第0行
// order by关键字 (用于排序,默认是进行升序排序)
select * from customers order by cust_id; // cust_id必须是int类型
select * from customers order by cust_id DESC; // DESC关键字使排序为降序
// 查找列cust_name为jeff的客户数据
select * from customers where cust_name = 'jeff';
// 查找除了jeff客户外其他客户的数据(使用 <> 和 != 关键字)
// 匹配范围内的数据,id大于3小于5 (and关键字以及between and )
select * from customers where id > 3 and id < 5;
select * from customers where id between 3 and 5;
// 还有OR关键字
// 查找表中Host为空数据和非空数据所在行
select * from customers where Host is null;
select * from customers where Host is not null;
// like操作符(like操作符搜索效率会比普通操作符来的慢)
select * from customers where cust_name like 'j%';
// %可以匹配{0,}次,即0-无数次任意字符,如jeff
select * from customer where cust_name like 'j_';
// _只能匹配单个字符,比如 ji
// 拼接字段(想返回 用户名字:用户描述 这样格式的内容可以使用concat关键字)
select concat(cust_name, ':',. cust_desc);
// 创建临时字段(临时列)
// 返回的表会创建一个临时列year_end_bonus,它每行的数据为该行的cust_salary * 5
select cust_salary*5 as year_end_bonus from customers;
Mysql的正则仅仅是完整正则中的一个子集。
// 最简单的正则匹配
select * from customers where cust_name regexp 'jeff';
// . 预定义符 . 可以用于匹配 0到无数个普通任意字符(不能匹配换行还是啥的。。。待更新)
select User from user where User regexp 'mysql.';
// | 进行or匹配
select User from user where cust_name regexp 'jeff | hzf';
// []进行或匹配
select * from user where cust_name regexp 'j[ji]'; // 能匹配到jj或者ji
// 特殊字符匹配
// 普通编程语言使用转义字符是使用一个反斜杠,sql中需要使用两个
\\n 用于匹配 \n转义字符
sql支持函数来处理数据
主要的几种数据库管理工具函数兼容性很差,使用时需要写好注释方便接盘以及谨慎使用。
// Date()函数用于年份处理
// 挑选出时间为2021-4-30到2022-9-1的数据
select * from customers where Date(time) between '2021-4-30' and '2022-9-1';
本文来自博客园,作者:xzjeff,为个人学习笔记。

浙公网安备 33010602011771号