問題描述
資料的儲存方式,一共經曆了三個階段。一人工管理階段:通過手寫将資訊儲存在石頭、竹簽、布、紙等材料上進行管理;二檔案管理階段:用電腦文本、word、excel等檔案進行儲存管理;三資料庫系統管理:将資訊寫入資料庫系統進行儲存管理。mysql資料庫是目前比較火的資料庫系統,它簡單、功能豐富、安全、快速、可視化。下面小編将簡單介紹mysql資料庫的基礎。
解決方案
mysql資料庫基礎小編總共分為兩個部分,本次介紹mysql資料庫基礎(一)。首先肯定是mysql的安裝(詳情請查閱上一期文章);操作部分為資料庫以及資料表相關操作、mysql操作資料表記錄、mysql資料庫查詢。
1資料庫安裝相關操作
圖1
2資料庫以及資料表相關操作
1)資料庫的相關指令:
查詢目前的登入的使用者:select current_user;
查詢目前的時間:select now();
顯示所有的資料庫:show databases;
檢測mysql安裝的版本:select version();
建立一個屬于自己的資料庫:create database +資料庫名稱;
删除資料庫:drop database +資料庫的名稱;
查詢資料庫,有則删除,無則不删除:
drop database if exists +資料庫名稱;
圖2
2)資料類型和限制:
圖3
圖4
圖5
3)資料表的相關指令:
進入資料庫:use +資料庫名稱
在資料庫中建立資料表:
create table stuinfo(
#定義列名 定義資料類型 定義元件 限制
id int primary key auto_increment,
name char(10) unique not null
tel varchar(11) not null unique
sex char(2) not null default(“男”) #預設性别為男
);
顯示資料表:show tables;
檢視表結構:desc +表名稱;
圖6
3mysql操作資料表記錄
1)插入資料表記錄
圖7
a.表中插入資料:
insert into books (bno,bname,author,price,quanitity)
values(1001,”紅樓夢”,“施耐庵”,15.6,100);
查詢表中所有列:
select * from +表名 (*代表查所有的列)
多條進行插入:
insert into books (bno,bname,author,price,quanitity)
values(1001,”紅樓夢”,“施耐庵”,15.6,100),
(1002,”三國演義”,“xxx”,15.6,50);
省略列名的插入:
insert into books values(1003,”三體”,“劉慈欣”,200,100);
外鍵限制:references
目前時間:now( )
圖8
2)查詢更改删除資料
查詢:select 屬性清單 from 表名 where 條件表達式;
select name ,price,quanitity from books;
select * from books where price>=30;
select * form books where author=”xxx”;
更新:update 表名 set 字段名1=字段值1,字段名2=字段值2,where (#條件表達式);
删除:delete form 表名 where條件表達式(不添加條件所有資料都被删除)。
4mysql資料庫查詢
1)資料表記錄進階查詢
a.查詢範圍條件 并列條件(and):select * from books where price >20 and price < 1000;
select * from books where pricebetween 20 and 1000;
b.或條件(or):select * from books where price<20 or price>100
查詢資訊表,列名用别名顯示:select 列名 as 别名 ,author as
作者 from 表名;select bname as(可省略) 書名 ,author as 作
者 from books;
c.表達式查詢:select price*quanitity form 表名(價格乘以數量)
order by 排序:select * form 表名 order by price desc(按照
價格降序排列);
select * form 表名 order by price asc(按照
價格升序排列);
d.limit 限制傳回結果的條數:
select * from 表名 limit 條數;(查詢幾條)
select * from 表名 limit 條數,條數;(查詢幾條到幾條)
e.排序和limit混合用法:select * from books order by price desc
limit 2;
f.distinct消除重複記錄:
select distinct 列名 from 表名;
g.like模糊查詢:
圖9
select * from 表名 where 列名 like “%xxx%”;
select * from 表名 where 列名 like “___x”;
h.聚合函數:
圖10
select sum(列名) as 總數量 from 表名;
select avg(列名) as 平均 from 表名;
select max(列名) as 最大值 from 表名;
select min(列名) as 最小值 from 表名;
select count(列名) as 總數 from 表名;
分組查詢 group by:
select * form 表名 group by 列名;
having子句(相當于where加條件,和聚合函數混合使用):
select 列名 from 表名 having 聚合函數() 條件
結語
mysql資料庫在navicat中進行運作管理有很多的注意事項。每一個操作指令都要以英文狀态下的分号結尾;資料庫中字母的大小寫是沒有影響的;需要正确使用字元類型和限制條件。下期小編将介紹mysql資料庫基礎(二),敬請期待。
end
主 編 | 王文星
責 編 | 江汪霖
where2go 團隊
微信号:算法與程式設計之美
長按識别二維碼關注我們!
溫馨提示:點選頁面右下角“寫留言”發表評論,期待您的參與!期待您的轉發!