MYSQL數據庫基礎

MYSQL數據庫基礎語句大全

#登錄[遠程]據庫
mysql -hlocalhost -uroot -p;

#修改密碼
mysqladmin -uroot -pold password new;

#顯示數據庫
show databases;

#顯示數據表
show tables;

#show語句的其他用法
show create database db_name;#顯示建庫結構
show create table tb_name\G;#顯示建表結構
show CHARACTER SET LIKE 'latin%';#SHOW CHARACTER SET語句用於顯示所有可用的字符集。
SHOW ENGINES\G;顯示存儲引擎的狀態信息,檢查存儲引擎是否被支持,查看默認引擎是什麼。

"\G"參數可格式化顯示結果;

#選擇數據庫
use examples;

注:window窗口字符界面亂碼
建議一般用utf8,window窗口下字符集是gbk,因此需要聲明字符集,如set names gbk;

#創建數據庫並設置編碼utf-8 多語言
create database `examples` default character set utf8 collate utf8_general_ci;

#刪除數據庫
drop database examples;

注:Mysql中,表/列可以改名,database不能改名. 
phpMyAdmin似乎有這功能? 是建新庫,把所有表複製到新庫,再刪舊庫完成的. 

#建表
查看當前庫下所有表: show tables;
create table test
(
 id int(10) unsigned zerofill not null auto_increment,
 email varchar(40) not null,
 ip varchar(15) not null,
 state int(10) not null default '-1',
 primary key (id)
)engine=InnoDB;

注意:
1.建表時爲什麼添加 not null default ''/default 0;
答:不想出現null值。
2.null值的缺點。
答:不好比較,null是一種類型,比較時只能用專門的is null 和is not null來比較。
碰到運算符一律返回null;
select null=null; 返回null
select null!=null; 返回null
效率不高,影響索引的檢索速度。


#刪除表: drop table stu;

#顯示錶結構
describe tb_name
show [full]columns from db_name.tb_name;

#刪除表數據
truncate tb_name;#清空表數據,相當於把原表刪除重新按原結構生成新表,自增索引從新開始
delete from tb_name where expir.. #把表數據刪除一部分

#重命名錶
alter table test_old rename test_new;
#添加列
alter table test add birth date not null default '0000-00-00'; 
alter table test add uname varchar(30) not null default '' after id;# 在id列之後插入列
alter table m1 add pid int not null default 0 first; #使用first 表字段將添加到第一列
#修改列
--modify修改列類型,語法:[alter table 表名 modify 列名 新類型 新參數]
alter table test modify gender char(4) not null default '';
--change修改列明及類型,語法:[alter table 表名 change 舊列名 新列名 新類型 新參數]
alter table test change id uid varchar(10) not null;

#刪除列
alter table test drop pid;

#在MySQL數據庫中拷貝數據表
在 MySQL 中拷貝表,將 old_table 表拷貝爲 new_table 表。
1. 不拷貝表數據,只拷貝結構。
CREATE TABLE new_table LIKE old_table
2. 通過 SELECT 查詢來拷貝,new_table 表會丟失主鍵、索引等信息。
引用
CREATE TABLE new_table AS
(
    SELECT *
    FROM old_table
)
3. 完全拷貝表
CREATE TABLE new_table LIKE old_table;
INSERT INTO new_table SELECT * FROM old_table;
4. 僅拷貝字段
CREATE TABLE new_table AS
(
    SELECT field1, field2 FROM old_table
)
5. 部分拷貝
CREATE TABLE new_table AS
(
    SELECT * FROM old_table WHERE field1 = test'
)
其他小技巧:
mysql>tee D:test.sql tee命令可將字符界面執行的sql語句和輸出結果保存到文件
mysql快速導入數據文件
mysql>use dbtest;
mysql>set names utf8;
mysql>set autocommit=0;
mysql>source D:/www/sql/back.sql;
通過source命令導入多個文件,可以新建一個test.sql文件,裏面存放下面的命令
source d:/a.sql;
source d:/b.sql;
運行
mysql>source D:/test.sql;
這樣就可以在一個source命令裏面導入多個sql文件了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章