mysql原生語句基礎知識
要操作數據庫,首先要登錄mysql:
*mysql -u root -p 密碼
創建數據庫:
*create database Runoob(數據庫名);
刪除數據庫:
*drop database Runoob;
選擇使用某個數據庫:
*use Runoob;
查看所有數據庫:
show databases;
創建數據表:
create table Table_name charset=utf8;
create table if not exists ‘Table_name‘(
‘id‘ int unsigned primaty key auto_increment,‘name‘ varchar(32) not null,
‘create_time‘ Date
)ENGING=InnoDB DEFAULT CHARSET=UTF8;
查看表結構:
desc Table_name;
刪除數據表:
drop table Table_name;
查看所有的表:
show tables;
insert into Table_name (filed1,filed2,...) values (value1, value2,...);
實例:
insert into Table_name (‘name‘,‘create_time‘) values (‘學習mysql‘, NOW());
查詢語句:
select column_name1, column_name2 from Table_name [where 條件] [limit n] [offset m]
1、通過limit屬性限制返回的數量
2、通過offset指定開始查詢的數據偏移量,默認是0
修改或更新數據:
update Table_name set field1=new_value1,field2=new_value2 [where 條件]
根據條件修改指定某條數據某些字段的值
實例:
1、將所有人的年齡加1 update students set age=age+1;
2、將id為5的手機號改為默認的-:update students set tel=default where id=5;3、將手機號為17521192856的姓名改為小馬:update students set name=‘小馬‘ where tel=‘17521192856‘;
使用update替換某個字段中的某個字符(批量修改指定字符串):
update Table_name set filed_name=replace(field_name, ‘old_value‘,‘new_value‘) [where 條件]
實例:
把表中所有name列的值為c++的值改為python
update Table_name set name=replace(name, ‘c++‘, ‘python‘);
刪除數據:
delete from Table_name [where 條件];
如果沒有指定where子句,將刪除表中的所有記錄
實例:delete from students where id=3;
模糊查詢:
sql like 子句中使用%來表示任意字符,類似於正則表達式中的*,如果沒有使用%,_表示一個占位字符,like子句與=的效果一樣。
select field1,field2... from Table_name where field1 like 條件1 [and [or]] field2=‘somevalue‘;
實例:
1、查詢name列中所有的包含COM的數據行
select * from students where name like ‘%COM‘;
union將不同表中相同列中查詢的數據展示出來(默認去重):
MySQL UNION 操作符用於連接兩個以上的 SELECT 語句的結果組合到一個結果集合中。多個 SELECT 語句會刪除重復的數據。
select field1, field2,... from table1 [where 條件] union [all] select field11, field22,... from table2 [where 條件] [order by field]
標簽:註:兩個select語句中至少有一個field一樣
實例:
select country from Websites union select country from apps order by country;去重
select country, name from Websites union all select country, app_name from apps order by country ASC;不去重
排序:
select field1,field2... from Table_name [where 條件] order by field1 desc;
聯合查詢
內連接inner join ... on ...
table1:
table2:
從以上兩張表來讀取table1表中所有runoob_author字段在table2表對應的runoob_count字段值:
select a.runoob_id,a.runoob_author,b.runoob_count from table1 as a inner join table2 on a.runoob_author = b.runoob_author;
等同於:
select a.runoob_id,a.runoob_author,b.runoob_count from table1 as a, table2 as b where a.runoob_author = b.runoob_author;
左連接left join ... on ...(獲取左側表的所有數據和右側滿足條件的數據) :
select a.runoob_id,a.runoob_author,b.runoob_count from table1 as a left join table2 as b on a.runoob_author = b.runoob_author;
右連接:
select a.runoob_id, a.runoob_author,b.runoob_count from table1 as a right join table2 as b on a.runoob_author = b.runoob_author;
mysql原生語句基礎知識