Mysql表連線-增刪改操作
1,概要說明:
MySQL表連線:用在當兩張表或者多張表聯合查詢,共同提供資料
Select e.id,d.id,d.name from emp as e
Join dep as d
On e.dpid = d.id
2,執行過程:
如果是 A join B則A為主表,B為從表
主表中的任何一條資料,都要試圖和從表中的每一行去連線,是否能夠真正連線,取決於on是否被滿足
on條件滿足後,主從雙方將自己對應的行,放入最終的大表中
3,分類:
內連線 [inner] join (ops : inner可以省略不寫)
外連線:
左外連線 left [outer] join
右外連線 right [outer] join (ops : outer可以省略不寫)B為主表
自連線 不區分連線方式,只不過是 連線的雙方是同一張表而已
外連線:主表資料全顯,如果沒有對方資料,用null填充
內連線:只有存在匹配資料的資料才會顯示在最終結果中
4,自連線演示:
select
t1.id,t1.level,t1.title,t2.title,t2.level
from
t_cate t1
JOIN
t_cate t2
ON
t1.id=t2.parent_id
5,多表連線:
SELECT
emp.*,dept.*,loc.*
FROM
t_employee emp
left JOIN
t_department dept
on
emp.dept_id = dept.id
right JOIN
t_location loc
on
loc.id = dept.loc_id;
6,聯合約束:
create table t_user(
id int auto_increment,
name varchar(20),
age tinyint,
nick varchar(20),
primary key(id,name), # id 和 name的組合作為聯合主鍵 (表級約束)
unique(age,nick) # age 和 nick 的組合不能重複 (表級約束)
)ENGINE = InnoDB default charset = utf8;
7,資料庫欄位資料型別:
數字
TINYINT 1 位元組 (-128,127)
SMALLINT 2 位元組(-32 768,32 767)
MEDIUMINT 3 位元組(-8 388 608,8 388 607)
INT或INTEGER 4 位元組(-2 147 483 648,2 147 483 647)
BIGINT 8 位元組(-9 233 372 036 854 775 808,9 223 372 036 854 775 807)
FLOAT 4 位元組(-3.402 823 466 E+38,-1.175 494 351 E-38)
DOUBLE 8 位元組(-1.797 693 134 862 315 7 E+308,-2.225 073 858 507 201 4 E-308)
DECIMAL 沒有固定大小 DECIMAL(m, n) 共m位其中小數n位,大小取決於m和n (沒有精度損失)
字元
CHAR 0-255位元組 定長字串
VARCHAR 0-65535 位元組變長字串
TINYBLOB 0-255位元組不超過 255 個字元的二進位制字串
TINYTEXT 0-255位元組短文字字串
BLOB 0-65 535位元組二進位制形式的長文字資料
TEXT 0-65 535位元組長文字資料
MEDIUMBLOB 0-16 777 215位元組二進位制形式的中等長度文字資料
MEDIUMTEXT 0-16 777 215位元組中等長度文字資料
LONGBLOB 0-4 294 967 295位元組二進位制形式的極大文字資料
LONGTEXT 0-4 294 967 295位元組極大文字資料
日期
DATE 日期值
DATETIME 日期和時間值
TIMESTAMP 日期和時間值
8,資料增刪改:
插入: insert into tabale_name (name,age) values(val1,val2);
插入多條:insert into tabale_name (name,age) values(val1,val2),
(val3,val2), (val3,val2);
可省略列名,但是後邊values必須順序一致:
Insert into table_name values(name,age,birth);
更新:
Update tables_name set name=’xxx’,age = 22 where id = 2;
update user9 set age=age+1,name=concat(name,age) where name not like '%j%';
刪除:
Delete from tables where name = ‘zhangsan’;
Delete form users;