MariaDB數據表操作實例


1. MariaDB 數據庫操作實例

MariaDB>create database class;  //創建class數據庫
MariaDB>use class;
MariaDB>create table class.student(  //創建student表
              id int(4) primary key,
              name varchar(4) not null,
              age int(2) not null,
              );
MariaDB>desc student;

MariaDB>alter table student add address varchar(48);  //添加address字段
MariaDB>alter table student add gender enum("boy","girl") after age;  //在age字段后面添加gender字段
MariaDB>alter table student change gender  
              sex ("boy","girl") not null;  //將gender字段名更改為sex
MariaDB>alert table student drop sex;  //刪除sex字段

2. MariaDB 索引創建與刪除

MariaDB 索引有普通索引、唯一索引、主鍵索引、自增主鍵索引.

MariaDB>create database erp;  //創建erp數據庫
MariaDB>create table erp.product(            //創建product表
            id int(4) not null,
            name varchar(8) not null,
            type enum("usefull","bad") not null,
            instruction  char(8) not null,
            index(id),index(name)
            );
MariaDB>desc product;
MariaDB>drop index name on product;   //刪除name字段的索引
MariaDB>create index shuoming on product(instruction);  //給指定字段創建索引
MariaDB>show inedx from erp.product\G;  //查看表的索引
MariaDB>create table price(              //建表時設置唯一索引
            id int(4),
            name varchar(4) not null,
            TTL int(4) not null,
            unique(id),unique(name),index(TTL)
            );
MariaDB>desc price;
MariaDB>drop index name on price;    //刪除索引
MariaDB>create unique index name on price(name);    //指定字段創建唯一索引

建表時設置主鍵索引

如果表內沒有主鍵字段, 則新設置的非空唯一索引字段相當於主鍵索引功能.

每個表的主鍵字段只能有一個.

MariaDB>create table test1(        //建表時指定主鍵字段
            id int(4) primary key,
            name varchar(8)
            );
MariaDB>create table test1(        
            id int(4),
            name varchar(8),
            primary key(id)
            );
MariaDB>create table test2(          //自增主鍵
            id int(4) auto_incremnet,
            name varchar(8) not null,
            age int(2) not null,
            primary key(id)
            );

MariaDB>alter table test1 drop primary key;    //刪除主鍵

MariaDB>alter table test2 modify id int(4) not null;    //test2中id字段有自增屬性,必須先去掉自增屬性才能刪除主鍵
MariaDB>alter table test2 drop primary key;
MariaDB>alter table test2 add primary key(id);    //指定字段添加主鍵

3. 外鍵同步更新與刪除

MariaDB>create table water(          //創建自增主鍵的表
            w_id int(4) auto_increment,
            name varchar(8) not null,
            primary key(id)
            );
MariaDB>create table river(              //river表中的r_id作為外鍵,water表中w_id作為參考鍵
            r_id int(4) not null,
            name varchar(8) not null,
            position float(7,2) not null default 0,
            index(name),
            foreign key(r_id) references water(w_id) on update cascade delete cascade
            );

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM