Linux应用开发————mysql数据库表

mysql数据库表操作

查看表的结构

mysql> desc / describe 表名;

或者:

mysql> show create table 表名;

常见数据库引擎: innodb, myISAM...

删除表

mysql> drop table if exists 表名 ;

表(结构)的修改

一般语法格式: alter table 表名 操作方式 数据

1. 修改表名称

mysql> alter table 表名 rename newtb;

2. 添加字段

mysql> alter table 表名 add 字段名 字段类型; 位置;
位置: 增加到最后

first:增加到第一列

after 已有字段: 增加到指定字段之后;

3. 修改字段名称:

mysql> alter table 表名 change 旧字段名 新字段名 字段类型;

4. 修改字段类型:

mysql> alter table 表名 modify 字段名 字段类型;

5. 修改字段顺序:

mysql> alter table 表名 modify 字段名 字段类型 位置;
位置:

first:增加到第一列

after 已有字段: 增加到指定字段之后;

删除字段

mysql> alter table 表名 drop 字段名 ;

设置约束

1) 设置 primary key / unique key

mysql> alter table 表名 add primary key / unique key (字段名) ;
2) 设置 not null 和 auto_increment

mysql> alter table 表名 modify 字段名 字段类型 not null / auto_increment;
3) default 约束

mysql> alter table 表名 alter 字段名 set default '默认值';
4) 外键约束

mysql> ALTER TABLE 表名 ADD CONSTRAINT 外键名 FOREIGN KEY(字段) REFERENCES 主表名(主键列) ON DELETE 参数

取消约束

1) 取消 primary key / foreign key

mysql> alter table 表名 drop primary key / foreign key;
2) 取消 unique key

mysql> alter table 表名 drop index 字段名;
3) 取消 default 约束

mysql> alter table 表名 alter 字段名 drop default;
4) 取消 not null 和 auto_increment

mysql> alter table 表名 modify 字段名 字段类型;

修改表中字段的字符集

mysql> alter table 表名 convert to character set utf8;

数据的操作

1. 数据增加

SQL 语句的语法格式:

insert into 表名 (字段1,字段2...) values (值11,值12...),(值21,值22...);

2. 数据删除

SQL 语句的语法格式:

delete from 表名 where 条件;

**特别注意:**数据删除时一定要指定条件,否则会删除所有数据;

条件如何构建:

MYSQL 提供了关系运算符和逻辑运算符: > < != = >= <= && || ! xor

3. 数据修改

SQL 语句的语法格式:

update 表名 set 字段1 = 值1,字段2 = 值2 where 条件;

4. 数据查询 (单表查询)

4.1 查看所有数据:

mysql> select * from 表名;

4.2 查看指定字段数据:

mysql> select 字段名1,字段名2... from 表名;

4.3 避免重复查询:

mysql> select distinct 字段名 from 表名;

4.4 空值查询

mysql> select 字段名 from 表名 where 字段 = NULL; error

mysql> select 字段名 from 表名 where 字段 is NULL; OK

4.5 条件查询

mysql> select 字段名,... from 表名 where 条件;

mysql> select 字段名,... from 表名 where 条件1 and 条件2;

4.6 范围查询

mysql> select 字段名,... from 表名 where 字段 between 值1 and 值2;

mysql> select 字段名,... from 表名 where 字段 not between 值1 and 值2;

相关推荐
无足鸟ICT11 分钟前
【RHCA+】who命令(查看已登陆用户)
linux·运维·服务器
Escalating_xu18 分钟前
【Linux 网络编程】应用层协议 HTTP(下):Header、连接管理与 C++ HTTP 服务器
linux·服务器·网络
十年程序梦1 小时前
2026最新国内省市区县表,mysql表格
mysql
Random Glow2 小时前
二级索引与回表:一次回表到底多贵
数据库·mysql·性能优化·innodb·索引
GeW3 小时前
新质生产力路线图落地,Linux运维与数据库架构师的机会清单
linux
Brilliantwxx3 小时前
【Linux】 文件访问与路径解析:目录、文件名、dentry、路径缓冲与 dcache 全解析
linux·运维·服务器·开发语言·spring
father_12273 小时前
Greenplum 集群故障恢复与主备同步机制实战
linux·网络·greenplum
ynchyong4 小时前
linux中的 sed` 与 `seq`
linux·运维·sed·seq·文本工具
sunburn-4 小时前
数据库聚合查询完整教程:从基础函数到实战统计
java·数据库·mysql·数据库开发
七牛云行业应用5 小时前
DeepSeek Harness(dsh)安装完整指南:Windows、macOS、Linux 三平台 + 桌面端与 Web 端全覆盖
linux·windows·macos·ai·ai编程