簡單常用的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';