MySQL数据库基础(6)表的操作

一、表操作

    1、指定字符集建库

        下面我们以默认格式的old库为例讲解,注意,由于我们并未特别设置数据库及客户端的字符集,因此,我们先指定字符集建库:

mysql> create database oldboy;
Query OK, 1 row affected (0.00 sec)

mysql> show create database oldboy;
+----------+-------------------------------------------------------------------+
| Database | Create Database                                                   |
+----------+-------------------------------------------------------------------+
| oldboy   | CREATE DATABASE `oldboy` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+-------------------------------------------------------------------+
1 row in set (0.00 sec)

     2、建立表

        1)建表的基本命令语法:

create table <表名><字段名1> <类型1>,
。。。
<字段名n> <类型n>
);

         2)建表语句:

        下面是人工写法设计的建表语句例子,表名student,

create table student(
id int(4) not null,
name char(20) not null,
age tinyint(2) not null default '0',
dept varchar(16) default null
);

         第二种MySQL生成的建表语句student表例子

mysql> show create table studentG
*************************** 1. row ***************************
       Table: student
Create Table: CREATE TABLE `student` (    
  `id` int(4) NOT NULL,
  `name` char(20) NOT NULL,
  `age` tinyint(2) NOT NULL DEFAULT '0',
  `dept` varchar(16) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)

         上述语句表示创建一个student表,有4个字段:

        需要注意的是:MySQL5.1和MySQL5.5环境的默认建表语句中的引擎的不同,如果希望控制表的引擎,就要在建表语句里显示的指定引擎建表:

        MySQL5.1及以前默认引擎为MyISAM,MySQL5.5.5以后默认引擎为InnoDB

        查看表结构

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(4)      | NO   |     | NULL    |       |
| name  | char(20)    | NO   |     | NULL    |       |
| age   | tinyint(2)  | NO   |     | 0       |       |
| dept  | varchar(16) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

     3、生产环境标准的UTF8格式表结构语句

        某sns产品生产正式建表语句

use sns;
set names gbk;
create table `subject_comment_manager`(
`subject_comment_manager_id` bigint(12) not null auto_increment comment '主键'
`subject_type` tinyint(2) not null comment '素材类型',
`subject_primary_key` varchar(255) not null comment '素材的主键',
`subject_title` varchar(255) not null comment '素材的名称',
`edit_user_nick` varchar(64) default null comment '修改人',
`edit_user_time` timetamp null default null comment '修改时间',
`edit_comment` varchar(255) default null comment '修改的理由',
`state` tinyint(1) not null default '1' comment '0代表关闭,1代表正常',
primary ket (`subject_comment_manager_id`),
key `IDX_PRIMARYKEY` (`subject_primary_key`(32)),     #括号内的32表示对前32个字符做前缀索引。
key `IDX_SUBJECT_TITLE` (`subject_title`(32)),
key `index_nick_type` (`edit_user_nick`(32),`subject_type`)       #联合索引,此行为新加的,用语给大家讲解的,实际表语句内没有此行。
);

    

原文地址:https://www.cnblogs.com/cnxy168/p/11589560.html