MySQL的語法,大小寫無關

MySQL指令
Command說明例子
use db_name;開啟資料庫use test2;
show tables;顯示資料庫中所有的tablessh tables;
show processlist;顯示每一筆連線show processlist -> go
show varibales;顯示MySQL的系統設定show varibales;
show indexshow index from books from test2;
show index from test2.books;
show table status;顯示連線的狀態show table status from test2;
show grants顯示使用者的權限show grants for user_name;
describe table_name;顯示table中所有的設定(含欄名,型態...)describe books;
explain table_name;同selectexplain books;

MySQL的函數
MySQL的函數函數說明例子
mysql_affected_rows();傳回最後影響的列數目
mysql_connect(dbhost,dbuser,dbpass)連接資料庫並得到一個Handlermysql_connect('test2','dbusr','abc123');
mysql_close();關閉與MYSQL的連線
mysql_create_db(db_name);建立一個新的dababase
mysql_data_seek($res,$row_number);移動內部傳回指標,再用mysql_fetch_row()叫出data
mysql_db_query(dbname,sql)執行sql的語法mysql_db_query('test2',"select * from books");
mysql_drop_db(db_name);刪除一個dababase
mysql_error()傳回錯誤訊息
mysql_escape_string()插入脫離字串,字串為保留字mysql_escape_string('%')
mysql_fetch_array(res);傳回一array內含整筆記錄
mysql_fetch_field(res);傳回一物件,內含欄名(name),型態(type)...$row = mysql_fetch_field(res);
print "$row->name";//顯示欄名
mysql_fetch_lengths();傳回各個欄位的最大值
mysql_fetch_row();傳回單列的欄位(同mysql_fetch_array)
mysql_field_name($res,$findex);指定欄位的名稱
(offset start from 0)
類似mysql_fetch_field()
mysql_field_type($res,$findex);指定欄位的資料屬性
(offset start from 0)
mysql_field_flags($res,$findex);指定欄位的特性
(primary key, not null...)
mysql_field_len($res,$f_offset);指定欄位的長度
mysql_field_seek($res,$f_offset);設定指標到傳回值的欄位,再用mysql_fetch_field()將data叫出
mysql_list_fields(dbname,dbtable,dbhandler)被指定的dbtable中的欄位數mysql_list_fields('test2','books',??)
mysql_num_fields()欄位數目 (field_offset)
mysql_num_rows()記錄的列數目 recno
mysql_query(sql,ptr)查詢query的idmysql_query("insert ...",$connection);
die()不成功時就Show...die("Can not execute sql!");
database()資料庫名稱
user(),system_user(),session_user()傳回使用者及主機名稱
password(str)將密碼加密
encrypt(str)將字串加密
encode/decode
get_lock(str,timeout)試著鎖定str, timeout秒若成功則true
release_lock(str)

MySQL支援的函數
函數函數說明例子
ascii(s1,s2,...)將文字依序轉為數字
bin(n)bin(n) = conv(n,10,2)
char(n1,n2,n3,...)將數字依序轉為文字
concat(x,y,...)傳回由x,y...組合成的字串
conv(n,from_base,to_base)將n有from_base進位的值轉為to_base進位的值
curdate(),curtime()各自傳回日期及時間,now()=curdate() & curtime()
dayofweek(date),weekday(date),dayname(date),dayofmonth(date),dayofyear(date)...
date_add(date,interval expr type),adddate()adddate("1999-12-31 23:59:55:, interval 5 second) = "2000-01-01 00:00:00"
date_sub(date,interval expr type),subdate()
elt(n,str1,str2,str3,...)當n=1傳回str1,2:str2...
field(str,str1,str2,str3,...)當str=str1傳回1,str=str2傳回2...
if(exp1,exp2,exp3)if exp1(TRUE)不為0或NULL則傳回exp2,否則傳回exp3
如果exp1為浮點則會先被轉為整數看待
ifnull(exp1,exp2)若exp1不為NULL則傳回exp1,否則傳回exp2
insert(str,pos,len,newstr)
instr(str,substr)同locate但是起始位置是0
left(str,len)/right從str左邊第一位元起傳回len長的字串
length(x)字串長度
locate(substr,str,n)從str的第n個次開始找和sbustr相同的起始位置
Lower(str), lcase(str),upper(str),ucase(str)
lpad(str,len,padstr)/rpad在str左邊一直padding padstr直到長度為len止
ltrim(strim)/rtrim/trim
mid(str,pos,len)mid('pronunciation',3,6) = 'onunci'
position(substr in str)同locate(substr,str,1) == locate(substr,str)
replace(str,from_str,to_str)replace('ashi','a','a-') = 'a-shi'
repeat(str,count)repeate('a',3) = 'aaa'
reverse(str) 倒著來
sec_to_time(secs)將secs秒轉為hh:mm:ss
space(n)填n個空格
strcmp(str1,str2)兩字串相互比較strcmp('test1','test2') = -1
strcmp('test2','test1') = 1
strcmp('test','test') = 0
substring(str,pos,len)substring('pronunciation',3,6) = 'onunci'
 
MySQL支援的函數(其他)
mod(a,b)floor(x)不大於x的最大整數ceiling(x)不小於x的最小整數
round(x)rand(x)least(a,b,c,d...)傳回最小的值
truncate(x)pow(x)greatest(a,b,c,d...)傳回最大的值

MySQL一般的資料型態
MySQL的資料型態儲存大小(Bytes)備註
int4
integer4同上
real8
float(4)4
float(8)8
decimal(m,d)m
numeric(m,d)m同上
date31000-01-01 ~ 9999-12-31
datetime8yyyy-mm-dd hh:mm:ss
time3hh:mm:ss
year1yyyy
timestamp14yyyymmddhhmmss
12yymmddhhmmss
10yymmddhhmm
8yyyymmdd
6yymmdd
char(m)m1~255
varchar(m)因值輸入的長度不同而變
text? + 2 ? < 2^16
set('value1','value2',...)1,2,3,4 or 8 group,值match其中就行

MySQL的四則運算
運算元 運算元運算元
+-*
MySQL的位元運算
運算元說明例子
& AND 18 & 12 = 0
| OR 18 | 12 = 30
<< 左移 22 << 11 = 45056
>> 右移 22 >> 11 = ?????
MySQL的邏輯運算
運算元說明
NOT (!) 0 = NOT (1+1) == ! (1+1) <> ! 1+1
OR (||)
AND (&&)
MySQL的比較運算
=<> or !=<=
>=><
between a and b True(1) when a ≤ x < b

SQL語法 (test2是db_name,books是tests中的tables之一)
SQL指令無大小寫之別,但是Table名稱則有
功能例子說明
create databasecreate database test2;
drop databasedrop database [if exists] test2;
use databaseuse test2;
create tablecreate [temporary] table books (
id int(5) not null auto_increment,
book_id char(8) not null,
name char(30) not null,
in_date date,
price int(3),
rent_price int(2),
unique (id),
primary key(book_id,id)
);
alter tablealter table books
change [column] name book_name char(35) not null,
add [column] publish_id char(5) after name,
drop index id,
drop primary key,
drop id,
add unique (book_id),
add primary key(book_id);
optimize tableoptimize table books;如果已經刪除很多資料或曾變動格式後用
create indexcerate unique index bk_index on books (book_id (8));
drop indexdrop unique index bk_index on books;
delete recorddelete [low_priority] from books where book_id ='12345678';指定low_priority會等沒有用戶端存取時才執行delete
select fromselect *
[into outfile 'bookdump'
fields terminated by ':'
enclose by '\']
from table
[where ...]
[group by col_name...] [having expr1]
[order by ...]
[procedure proc_name]
有順序性,傳回的第一筆編號0
insert recinsert into books (book_id,book_name) values('12345679','C++');
replace recreplace [low_priority] books (book_id,book_name) values('12345679','Visual C++');當遇到unique欄位重複時,insert會出現問題,但是replace則會將舊資料排除再新增此筆資料
load data infileload data infile "./tmp.txt" into table books
fields terminated by "::"
(book_id,name,...);
將text file一筆筆寫進資料庫
update recupdate [low_priority] books set book_name="VB" where book_id = "12345679";
flushflush host[,logs,privileges,talbes,status];
killkill proc_id;刪除某一連線
lock/unlocklock tables books [read/write]如果指定read則所有要求連線的使用者都可以讀books
如果使用者a指定write則除了user a可以讀寫外,其他使用者都只能queue到users a unlock table
setset password for bob@"%.test.net" = password("ttt1234");
update mysql.user set password=password("ttt1234") where user="bob";
grant/revokegrant priv_type [(column_list)]
on {tbl_name| db_name}
To bob [ientified by 'ttt1234']

revoke priv_type [(column_list)]
on {tbl_name| db_name}
From bob [,user_name...]

eg: grant SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER on db_name.* to db_user@localhost identified by 'db_password';

四等級:Global
database
table
Column

權限(priv_type):

all
file
reload
alter
index
select
greate
insert
shutdown
delete
process
update
drop
usage
references
drop tabledrop [if exists] books;