#DDL
/*
data definition language
Library and table management
1. Library management
Create, modify, delete
2. Table management
Create, modify, delete
Create: create
Modify: alter
Delete: drop
*/
#1. Library management
#1. Library creation
/*
Syntax:
create database [if not exists] library name;
*/
#Case: create library Books
CREATE DATABASE IF NOT EXISTS books ;
#2, library modification
RENAME DATABASE books TO new library name; #Modification is generally not supported now, it is best not to change
#Change the character set of the library
ALTER DATABASE books CHARACTER SET gbk;
#3, library deletion
DROP DATABASE IF EXISTS books;
#2. Table management
#1. Table creation★
/*
Syntax:
create table table name (
column name column type [(length) constraint],
column name column type [(length) constraint],
column name column type [(length) constraint],
...
column name Column type [(length) constraint]
)
*/
#Case: create table Book
CREATE TABLE book(
id INT, #number
bName VARCHAR(20), #book name
price DOUBLE, #price
authorId INT, #author number
publishDate DATETIME#publication date
);
DESC book;
#Case: create table author
CREATE TABLE IF NOT EXISTS author(
id INT,
au_name VARCHAR(20),
nation VARCHAR(10)
);
DESC author;
#2. Table modification
/*
Syntax
alter table table name add|drop|modify|change column column name [column type constraint];
*/
#①Modify column name
ALTER TABLE book CHANGE COLUMN publishdate pubDate DATETIME;
#②Modify the column type or constraint
ALTER TABLE book MODIFY COLUMN pubdate TIMESTAMP;
#(3)
ALTER TABLE author ADD COLUMN annual DOUBLE;
#④Delete column
ALTER TABLE book_author DROP COLUMN annual;
#⑤ Modify table name
ALTER TABLE author RENAME TO book_author;
DESC book;
#3. Table deletion
DROP TABLE IF EXISTS author;
#View all tables in the current library
SHOW TABLES;
#Create a new library/table general way of writing------delete the old one first------
DROP DATABASE IF EXISTS old library name;
CREATE DATABASE new library name;
DROP TABLE IF EXISTS old table name;
CREATE TABLE table name();
#4. Table replication
INSERT INTO author VALUES
(1,'Murakami Haruki','Japan'),
(2,'Mo Yan','China'),
(3,'Feng Tang','China'),
(4,'Jin Yong', 'China');
DESC author; #Display the attributes of the table
SELECT * FROM Author;
SELECT * FROM copy2;
#1. Just copy the structure of the table
CREATE TABLE copy LIKE author;
#2. Copy table structure + data
CREATE TABLE copy2
SELECT * FROM author;
#Copy only part of the data
CREATE TABLE copy3
SELECT id,au_name
FROM author
WHERE nation='China';
#Only copy certain fields ----- non-zero is true -----
CREATE TABLE copy4
SELECT id, au_name
FROM author
WHERE 0;
SELECT * FROM copy4;