2018年10月2日 星期二

MySQL Note

MySQL Note

MySQL 筆記

連結資料庫(使用cli)

官方提供的cli:

shell> mysql -u <username> -p

使用mycli

shell> mycli -u <username>

常用資料庫操作

新增資料庫

create database <database name>;

移除資料庫

drop database <database name>;

使用資料庫

use <database name>;

顯示所有資料庫

show database;

修改密碼

ALTER USER <name>@<host> IDENTIFIED BY <new_password>;

常用資料表操作

新增、移除、修改資料表:

新增資料表

CREATE TABLE cats
(
  id              INT unsigned NOT NULL AUTO_INCREMENT, # Unique ID for the record
  name            VARCHAR(150) NOT NULL,                # Name of the cat
  owner           VARCHAR(150) NOT NULL,                # Owner of the cat
  birth           DATE NOT NULL,                        # Birthday of the cat
  PRIMARY KEY     (id)                                  # Make the id the primary key
);

相關資料型別

移除資料表:

drop table <table_name> rename 

修改資料表:

alter table <table_name> add <column_name> <data_type>;
alter table <table_name> drop <column_name> <data_type>;

修改資料表名:

alter table <old_table_name> rename to <new_table_name>;
rename table <old_table_name> to <new_table_name>;

顯示目前使用的資料庫中所有的資料表:

SHOW TABLES;

columns相關操作

顯示全部的columns

describe <table_name>;

顯示單一column

describe <table_name> <column_name>;

修改column名

alter table <table_name> rename column <old_column_name> to <new_column_name>;

修改column資料型別

alter table <table_name> modlty <column_name> <new_datatype>;

資料操作

選取資料表中全部的資料

select * from <table_name>;

按照條件選取

select * from <table_name> where <condition>;

例:

select name from comics where id==123;
select * from comics where title is NULL;

移除特定資料:

delete from <table_name> where <condition>;

插入資料(輸入的值須符合型別)

insert into <table_name> (column_name1, column_name2,...,) values (data1, data2....);

修改資料

update <table_name>
set <column_name1>=<new_value1>,
    <column_name2>=<new_value2>
where <condition>

從.sql file匯入

source <path_of_sqlfile>

外鍵(FOREIGN KEY

FOREIGN KEY (<local_table_column>) REFERENCES <foreign_table> (<foreign_table_primary_key_name>)

Reference

  1. Getting Started with MySQL
  2. MySQL 8.0 Reference Manual
  3. SQL語法教學

沒有留言:

張貼留言