安裝¶
sudo apt-get install mysql
命令行操作¶
登錄¶
mysql -u用戶名 -p密碼 -h數(shù)據(jù)庫地址(ip) 數(shù)據(jù)庫名稱
注意:盡量不要在-p后直接跟密碼,否則其他人很容易通過查閱命令行歷史記錄(比如,history命令)看到你的密碼。
SQL參考¶
MySQL參考¶
常見數(shù)據(jù)類型¶
integer(11) 11位字節(jié)的整數(shù)
tinyint(1)
bigint(20)
decimal(10,2) 小數(shù)
varchar(20) 最長為20位字節(jié)的可變字符串
char(20) 最長為20位字節(jié)的定長字符串(定長指的是存儲(chǔ)空間定長)
text 文本,用于存大量不固定長度的文本信息
blob 二級(jí)制信息
常見函數(shù)¶
length(str) 字符串的長度
trim(str) 去掉字符串前后的空格
substring(str,1) 獲取子串
convert(str using gbk) 將字符串轉(zhuǎn)化為gbk編碼
reverse(str) 倒序
增刪改查¶
insert into product (sku,name) values ('123456','productname')
向表中添加sku=123456,name='productname' 的數(shù)據(jù)
update product set name='updated product name' where sku='123456'
將表product中的sku為'123456'的數(shù)據(jù)的name字段的值設(shè)置為'updated product name'
select sku,name from product where sku='123456'
從表product 中查詢 sku為'123456'的數(shù)據(jù)
delete from product where sku='123456'
其他操作實(shí)例¶
多表查詢¶
select p.sku,b.name from product p,brand b where p.brand_id=b.id and p.sku='123456'
子查詢¶
select p.sku,p.name from product p where p.brand_id in (select id from brand where id=123)
左連接¶
select p.sku,p.name,b.name from product p left join brand b on p.brand_id=b.id
從一個(gè)表導(dǎo)入數(shù)據(jù)到另一個(gè)表¶
insert into product1 (sku,name,brand_id) (select sku,name,brand_id from product2)
查找不同的數(shù)據(jù)¶
select distinct p.sku from product p
查詢時(shí)按照某個(gè)字段排序(asc升序,desc降序)¶
select * from product order by name desc
常見問題¶
如何創(chuàng)建表¶
CREATE TABLE product (
`sku` char(6) NOT NULL COMMENT '商品的唯一標(biāo)識(shí)\n',
`brand_id` int(11) default NULL,
`name` varchar(50) default NULL,
PRIMARY KEY (`sku`),
CONSTRAINT `brand_fk_constraint` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
如何創(chuàng)建外鍵¶
alter table product add CONSTRAINT `brand_fk_constraint` FOREIGN KEY (`brand_id`) REFERENCES `brand` (`id`)
如何修改表中的字段¶
alter table product modify name varchar(200)
如何向表中添加字段¶
alter table product add comment varchar(200)
如何刪除表中字段¶
alter table product drop name
存儲(chǔ)過程和觸發(fā)器¶
h3.mysql創(chuàng)建表
drop table if exists news;
/*==========================*/
/* Table: 消息表 */
/*==========================*/
create table news
(
NewsId bigint(20) not null unsigned primary key auto_increment,
NewsContext varchar(50) not null,
NewsType varchar(50) not null,
UsersId int(11) not null
);
alter table news add constraint FK_Id foreign key (NewsId)
references users (UsersId);