随笔-31  评论-2  文章-0  trackbacks-0

安装

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 阅读(109) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: