增加删除列
添加一列
alter table teacher add class_id int null;
//增加 teacher 列表 class_id 列 里面可以为空
删除一列
ALTER TABLE 表名字 DROP COLUMN 列名字;
或: ALTER TABLE 表名字 DROP 列名字;
修改列
重命名一列
//这条语句其实不只可用于重命名一列,准确地说,它是对一个列做修改(CHANGE) :
ALTER TABLE 表名字 CHANGE 原列名 新列名 数据类型 约束;
注意:这条重命名语句后面的 “数据类型” 不能省略,否则重命名失败。
对表的内容修改
(1)修改表中某个值
//大多数时候我们需要做修改的不会是整个数据库或整张表,而是表中的某一个或几个数据,这就需要我们用下面这条命令达到精确的修改:
UPDATE 表名字 SET 列1=值1,列2=值2 WHERE 条件;
//mysql> update teacher set class_id=1 ;
//整列都变成了1
//mysql> update teacher set class_id=1 where id=1;
// class_id值是1 ,加个条件id是1的改成1.
添加主键
alter table 表名 add primary key(列名;
alter table students add id int not null auto_increment, add primary key (id);
(图片)
image.png
查看是否关联
mysql> select * from teacher a , class b where a.class_id=b.id;
+----+--------------+------+-------------+----------+----+---------------+
| id | name | age | phone | class_id | id | name |
+----+--------------+------+-------------+----------+----+---------------+
| 1 | 美丽芳姐 | 18 | 13141314130 | 1 | 1 | 云计算1810 |
+----+--------------+------+-------------+----------+----+---------------+
1 row in set (0.00 sec)
````select * from teacher a , class b where a.class_id=b.id;
//从 teacher表 a , class表 b where a.列=b.列 ;
内容相同的将会显示出来
单表查询
基础查询
select * from 表
select * from 表 where id > 2
select id,name,age as gg from 表 where id > 2
高级查询
a、条件
select * from 表 where id > 1 and name != '王麻子' and age = 18;
select * from 表 where id between 5 and 16;
select * from 表 where id in (11,22,33)
select * from 表 where id not in (11,22,33)
select * from 表 where id in (select id from 表)
b、通配符
select * from 表 where name like 'sha%' - sha开头的所有(多个字符串)
select * from 表 where name like 'shar_' - sha开头的所有(一个字符)
c、限制
select * from 表 limit 5; - 获取前 5 行
select * from 表 limit 0,2; - 从第 1 行开始, 取出 2 行, 包含第 1 行
select * from 表 limit 2 offset 0 - 从第 1 行开始, 取出 2 行, 包含第 1 行
d、排序
select * from 表 order by 列 asc - 根据 “列” 从小到大排列
select * from 表 order by 列 desc - 根据 “列” 从大到小排列
select * from 表 order by 列1 desc,列2 asc - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序
e、分组
select age from 表 group by age
select age,id from 表 group by age,id
select age,id from 表 where id > 10 group by age,id order id desc
select age,id,count(*),sum(age),max(age),min(age) from 表 group by age,id
select age from 表 group by age having max(id) > 10
特别的:group by 必须在where之后,order by之前
f、嵌套查询
select * from (select name from t1 where age>18 and age < 25 order by id desc limit 2 ) as tt order by id;
例图:
//按年龄排序
image.png
// %代替多个字符
image.png
//查看删除表
image.png
//多建表创建
image.png
//多键表填入
image.png
//查询
image.png
image.png