MySQL數據庫和表的命令行基本操作語法

1.登錄MySQL

  1. 在命令行中登錄MySQL

mysql -uroot -proot

2.數據庫的基本操作

  1. 創建數據庫

create database 數據庫名字;

  1. 刪除數據庫

drop database 數據庫名字;

  1. 查看所有數據庫

show databases;

  1. 查看數據庫定義

show create database 數據庫名字;

  1. 查看當前正在使用的數據庫

select databse();

  1. 使用數據庫

use 數據庫名字;

  1. 修改數據庫

alter database character set 字符集;

3.關於數據表的基本操作

  1. 創建表

create table 表名(
列名1 列的類型(長度) 約束,
列名2 列的類型(長度) 約束
);

  1. 約束類型

主鍵約束 primary key;
非空約束 not null;
唯一約束 unique;

  1. 刪除表

drop table 表名;

  1. 修改表

添加列
alter table 表名 add 列名 列的類型(長度) 約束;
刪除列
alter table 表名 drop 列名;
修改列名
alter table 表名 change 舊列名 新列名 列的類型(長度) 約束;
修改表的字符集
alter table 表名 character set 字符集;
修改表名
rename table 舊錶名 新表名;

  1. 查看當前數據庫所有的表

show tables;

  1. 查看錶的定義結構/創建語句

show create table 表名;

  1. 查看錶的結構

desc 表名;

4.表中數據的基本操作

  1. 插入數據

insert into 表名(列名1,列名2) values(值1,值2);
insert into 表名 values(值1,值2);
批量插入
insert into 表名 values(值1,值2),values(值1,值2),values(值1,值2);

  1. 刪除數據

delete from 表名 where 條件;
truncate table 表名;

  1. 更新數據

update 表名 set 列名1=值1,列名2=值2 where 條件;

  1. 查詢數據(以下以表名=product 列名1=pid 列名2=pname 列名3=price爲例)

簡單查詢
select * from 表名;
select 列名1,列名2 from 表名;
as查詢(as 關鍵字可以省略)
select p.pname,p.price from pruduct as p;
select pname as 商品名稱,price as 商品價格 from product;
去掉重複的值查詢
select price from product;
select distince price from product;
運算查詢
select price1.5 from product;
條件查詢
select * from 表名 where 條件;
select * from product where price > 60;
查詢price不等於8的
select * from product where price !=8;
select * from product where peice <> 8;
查詢price在10到20之間的
select * from product where price>10 and price<20;
select * from product where price between 10 and 20;
模糊查詢(like)
%:代表多個字符
_:代表一個字符
select * from product where pname = %酒;
select * from product where pname = _酒%;
in在某個範圍之內查詢
select * from product where pid in (1,2,3);
排序查詢
升序
select * from product order by price asc;
降序
select * from product order by price desc;
聚合函數
select sum(price) from product;
select avg(price) from product;
select count(
) from product;
分組查詢(以某一個值爲一組,這裏以id 爲例)
select id,count(*) from product group by id having avg(price)>10;
關鍵字
having 分組查詢之後可以跟having關鍵字。
where 出現咋分組查詢之前,不可以接聚合函數。
編寫順序
select…from…where…group by…having…order by…;
執行順序
from…where…group by…having…select…order by…;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章