从前有匹马叫代码
心若没有栖息的地方,到哪里都是流浪

创建一个数据库

CREATE DATABASE IF NOT EXISTS sql_example

删除一个数据库

DROP DATABASE IF EXISTS sql_example

创建数据表

USE sql_example;
DROP TABLE IF EXISTS customers;

CREATE TABLE customers (
    customer_id INT PRIMARY KEY AUTO INCREMENT,
    first_name VARCHAR(50) NOT NULL
)

修改数据表

ALTER TABLE customers
    ADD city VARCHAR(50) NOT NULL AFTER first_name,
    MODIFY first_name VARCHAR(45) NOT NULL,
    DROP email;

删除数据表

DROP TABLE IF EXISTS customers;

创建关系

点击查看代码
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS customers;

CREATE TABLE customers (
	customer_id INT PRIMARY KEY AUTO_INCREMENT,
  	first_name VARCHAR(50) NOT NULL,
  	last_name VARCHAR(50) NOT NULL,
);

CREATE TABLE orders (
	customer_id INT NOT NULL,
  	order_id INT PRIMARY KEY,
  	FOREIGN KEY fk_orders_customers(customer_id)
  	REFERENCES customers (customer_id)
  	ON UPDATE CASCADE
  	ON DELETE NO ACTION
)

说明:FOREIGN KEY 外键名字 (添加外键的列), REFERENCES 关联的表 (关联的字段) ON UPDATE 操作 ON DELETE 操作

posted on 2021-10-05 19:41  从前有匹马叫代码  阅读(73)  评论(0编辑  收藏  举报