mysql初体验学习笔记_MySQL数据库初体验
克隆表,將數(shù)據(jù)表的數(shù)據(jù)記錄生成到新的表中
方法一:
create table test01 like GCC01; #通過(guò) LIKE 方法,復(fù)制GCC01表結(jié)構(gòu)生成test01表
insert into test01 select * from GCC01;
方法二:
CREATE TABLE test02 (SELECT * from GCC01);
show create table test02\G #獲取數(shù)據(jù)表的表結(jié)構(gòu)、索引等信息
SELECT * from test02;
清空表,刪除表內(nèi)的所有數(shù)據(jù)
方法一
delete from test01;
#DELETE清空表后,返回的結(jié)果內(nèi)有刪除的記錄條目;DELETE工作時(shí)是一行一行的刪除記錄數(shù)據(jù)的;如果表中有自增長(zhǎng)字段,使用DELETE FROM刪除所有記錄后,再次新添加的記錄會(huì)從原來(lái)最大的記錄ID后面繼續(xù)自增寫入記錄。
方法二:
truncate table test01;
#TRUNCATE清空表后,沒有返回被刪除的條目;TRUNCATE工作時(shí)是將表結(jié)構(gòu)按原樣重新建立,因此在速度上TRUNCATE會(huì)比DELETE清空表快;使用TRUNCATE TABLE清空表內(nèi)數(shù)據(jù)后,ID會(huì)從1開始重新記錄。
創(chuàng)建臨時(shí)表
臨時(shí)表創(chuàng)建成功之后,使用 SHOW TABLES 命令是看不到創(chuàng)建的臨時(shí)表的,臨時(shí)表會(huì)在連接退出后被銷毀。
如果在退出連接之前,也可以可執(zhí)行增刪改查等操作,比如使用DROP TABLE語(yǔ)句手動(dòng)直接刪除臨時(shí)表。
CREATE TEMPORARY TABLE 表名 (字段1 數(shù)據(jù)類型,字段2 數(shù)據(jù)類型[,...][,PRIMARY KEY (主鍵名)]);
例:
create temporary table test03 (
id int(4) zerofill primary key auto_increment,
name varchar(10) not null,
cardid int(18) not null unique key,
hobby varchar (50));
insert into test03 values (1,'zhangsan‘,123456,'running’);
select * from test03;
show tables;
quit
select * from test03;
創(chuàng)建外鍵約束,保證數(shù)據(jù)的完整性和一致性
外鍵的定義:如果同一個(gè)屬性字段X在表一中是主鍵,而在表二不是主鍵,則字段X稱為表二的外鍵。
主鍵表和外鍵表的理解:
(1)、以公共關(guān)鍵字作主鍵的表為主鍵表(父表,主表)
(2)、以公共關(guān)鍵字作外鍵的表為外鍵表(從表、外表)
注意:與外鍵關(guān)聯(lián)的主表的字段必須設(shè)置為主鍵。要求從表不能是臨時(shí)表,主從表的字段具備相同的數(shù)據(jù)類型、字符長(zhǎng)度和約束。
#創(chuàng)建主表test04
create table test04 (hobid int(4),hobname varchar(50));
#創(chuàng)建從表test05
create table test05 (id int(4) primary key auto_increment,name varchar(10),age int(3),hobid int(4));
#為主表test04添加一個(gè)主鍵約束。主鍵名建議以 “PK_” 開頭。
alter table test04 add constraint PK_hobid primary key (hobid);
#為從表test05表添加外鍵,并將test05 表的hobid 字段和test04 表的hobid字段建立外鍵關(guān)聯(lián)。外鍵名建議以 “FK_” 開頭。
alter table test05 add constraint FK_hob foreign key (hobid) references test04 (hobid);
desc test05;
#插入新的數(shù)據(jù)記錄時(shí),要先主表再?gòu)谋?/p>
insert into test04 values(1,'runing');
insert into test05 values(1,'zhangsan',18,1);
#刪數(shù)數(shù)據(jù)記錄時(shí),要先從表再主表,也就是說(shuō)刪除主鍵表時(shí)必須先刪除其他與之關(guān)聯(lián)的表。
drop tables test05;
drop tables test04;
#查看和刪除外鍵約束
show create table test05; .
alter table test05 drop foreign key FK_hob;
alter table test05 drop key FK_hob;
desc test05;
MySQL中6種常見的約束:
主鍵約束(primary key)
外鍵約束(foreign key)
非空約束(not null)
唯一性約束(unique [key|index] )
默認(rèn)值約束(default)
自增約束(auto_increment)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的mysql初体验学习笔记_MySQL数据库初体验的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 大宇经典游戏《轩辕剑叁 云和山的彼端》今
- 下一篇: 鸿蒙领衔 华为小米OPPOvivo都将在