sudo apt-get install mysql
命令行操作¶
mysql -u用戶名 -p密碼 -h數據庫地址(ip) 數據庫名稱
注意:盡量不要在-p后直接跟密碼,否則其他人很容易通過查閱命令行歷史記錄(比如,history命令)看到你的密碼。
SQL參考¶
MySQL參考¶
常見數據類型¶
integer(11) 11位字節的整數
tinyint(1)
bigint(20)
decimal(10,2) 小數
varchar(20) 最長為20位字節的可變字符串
char(20) 最長為20位字節的定長字符串(定長指的是存儲空間定長)
text 文本,用于存大量不固定長度的文本信息
blob 二級制信息
常見函數¶
length(str) 字符串的長度
trim(str) 去掉字符串前后的空格
substring(str,1) 獲取子串
convert(str using gbk) 將字符串轉化為gbk編碼
reverse(str) 倒序
增刪改查¶
insert into product (sku,name) values ('123456','productname')
向表中添加sku=123456,name='productname' 的數據
update product set name='updated product name' where sku='123456'
將表product中的sku為'123456'的數據的name字段的值設置為'updated product name'
select sku,name from product where sku='123456'
從表product 中查詢 sku為'123456'的數據
delete from product where sku='123456'
其他操作實例¶
多表查詢¶
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
從一個表導入數據到另一個表¶
insert into product1 (sku,name,brand_id) (select sku,name,brand_id from product2)
查找不同的數據¶
select distinct p.sku from product p
查詢時按照某個字段排序(asc升序,desc降序)¶
select * from product order by name desc
常見問題¶
如何創建表¶
CREATE TABLE product (
`sku` char(6) NOT NULL COMMENT '商品的唯一標識\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
如何創建外鍵¶
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
存儲過程和觸發器¶
h3.mysql創建表
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);
官方參考:http://dev.mysql.com/doc/
posted on 2009-07-02 09:38
xiaoxinchen 閱讀(118)
評論(0) 編輯 收藏