1. 程式人生 > >mysql庫和表的案例

mysql庫和表的案例

mysql庫和表的案例

直接po程式碼

#庫和表的案例

USE shoppingCart;

#1.建立表dept1
/*

NAME	NULL?	TYPE
id		INT(7)
NAME		VARCHAR(25)

*/

#
CREATE TABLE dept1(
	id INT(7),
	`name` VARCHAR(25)
);
#
SELECT * FROM dept1;

#2.將表departments中的資料插入新表dept2中(可以跨庫)
CREATE TABLE dept2 SELECT department_id, department_name FROM myemployees.departments;
#
SELECT * FROM dept2;
#
INSERT INTO dept1 SELECT department_id, department_name FROM myemployees.departments;
#
SELECT * FROM dept1;

#3.建立表emp5
/*
NAME	NULL?	TYPE
id		INT(7)
First_name	VARCHAR (25)
Last_name	VARCHAR(25)
Dept_id		INT(7)
*/
CREATE TABLE IF NOT EXISTS emp5(
	id INT(7),
	First_name VARCHAR (25),
	Last_name VARCHAR(25),
	Dept_id	INT(7)
);
#
DESC emp5;
#
SELECT * FROM emp5;

#4.將列Last_name的長度增加到50
ALTER TABLE emp5 MODIFY COLUMN Last_name VARCHAR(50);

#5.根據表employees建立employees2
#
CREATE TABLE employees2 LIKE myemployees.employees;
#使用IF NOT EXISTS提高容錯性
CREATE TABLE IF NOT EXISTS employees2 LIKE myemployees.employees;
#
DESC employees2;
#(僅僅複製了表的結構,沒有複製資料)
SELECT * FROM employees2;
#

#6.刪除表emp5
DROP TABLE IF EXISTS emp5;

#7.將表employees2重新命名為emp5
ALTER TABLE employees2 RENAME TO emp5;

#8.在表dept和emp5中新增新列test_column,並檢查所作的操作
ALTER TABLE emp5 ADD COLUMN test_column INT(30);
#
DESC emp5;
#
SELECT * FROM emp5;

#9.直接刪除表emp5中的列test_column
ALTER TABLE emp5 DROP COLUMN test_column;
#
DESC emp5;
#
SELECT * FROM emp5;