**MySQL中的数据类型**
MySQL有三大类数据类型, 分别为数字、日期\时间、字符串:
*数字类型*
整数: tinyint、smallint、mediumint、int、bigint
浮点数: float、double、real、decimal
*日期和时间*: date、time、datetime、timestamp、year
*字符串类型
*字符串: char、varchar
文本: tinytext、text、mediumtext、longtext
二进制(可用来存储图片、音乐等): tinyblob、blob、mediumblob、longblob
**创建一个数据库**
create database 数据库名 [其他选项];
例:create database db_myproject;
**创建数据库表**
create table 表名称( 列名 类型 约束)
例:
create table users (
user_id int auto_increment primary key,
user_name varchar(20) not null,
user_gender varchar(4) not null );
查询表中的数据
select 列名称 from 表名称 [查询条件];
按特定条件查询:select 列名称 from 表名称 where 条件;
向表中插入数据
insert into 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...);
例:insert into users values(NULL, "张三", "男", 20, "13454341377");
更新表中的数据
update 表名称 set 列名称=新值 where 更新条件;
例:update users set tel=‘13412312345’ where id=5;
删除表中的数据
delete from 表名称;
**表的修改**
添加列:
alter table 表名 add 列名 列数据类型 [after 插入位置];
例:alter table users add address char(60);
修改列:
alter table 表名 change 列名称 列新名称 新数据类型;
将表 tel 列改名为 telphone: alter table users change tel telphone char(13);
删除列: alter table 表名 drop 列名称;
例:alter table students drop birthday;
重命名表:
alter table 表名 rename 新表名;
删除整张表:
drop database 数据库名;
多表联查:
1:内联接 inner join(返回两张表都匹配的数据)
select u.user_id,u.user_name,inf.userInfor_tel from users u join userInfor inf on u.user_id = inf.user_id
2:左外联接 left join(返回左表所有数据)
select u.user_id,u.user_name,inf.userInfor_email from users u LEFT JOIN userInfor inf on u.user_id = inf.user_id
3:右外联接 right join(返回右表所有数据)
select u.user_id,u.user_name,inf.userInfor_email from users u RIGHT JOIN userInfor inf on u.user_id = inf.user_id
添加主键约束:
1:建表时添加
create table userInfor(
userInfor_id int PRIMARY KEY auto_increment,
userInfor_tel VARCHAR(20),
userInfor_email VARCHAR(20),
user_id int,
CONSTRAINT FK_userId FOREIGN key(user_id) REFERENCES users(user_id)
)