02_MySQL的基本操作

主要内容:

  • 常用命令
  • 数据类型
  • DDL操作
  • DML语句
  • DCL语句

常用命令

  1. 登录、退出

    • 登录:mysql -u usrName -p
    • 退出:exit:回车 || quit || \p
  2. 查看

    • select now();(查看当前时间)
    • select curdate();
    • select curtime();
    • select version();
    • select user();
  3. 数据库

    • 查看数据库:show databases;。系统自建的数据库:
      • infomation_schema:数据库对象信息,如用户表、列信息、权限、字符集、分区信息等。
      • mysql:存储系统的用户权限信息。
      • sys和performance_schema
    • 创建:create database dbname;
      • eg: create database demo;
    • 删除:drop database dbname;
      • eg: drop database demo;
    • 使用:use dbname; /进入数据库中

数据类型

  1. 整型int:
    1. tinyint 【占1字节:有符号-128~127;无符号:0-255】 表示年龄可以,小数据。
    2. smallint 【有符号:-3276832767;无符号:065535】
    3. int 【占4字节:10位数】
    4. BIGINT 【8字节】

    注:bool == tinyint 1

  2. 浮点型float:
    1. float 4字节 日常生活小数 【会丢失精度】
    2. double 4字节 用不到
    3. DECIMAL[m,d] m总位数,d小数点后的位数。【不会丢失精度】
  3. 字符串
    1. char(位数) 定长字符:225
    2. varchar(位数) 变长字符【常用】
    3. text 65535个字符
    4. MEDIUMBLOB 2的24方字符
    5. enum(val1,val2,val3...)枚举 【eg:enum(“男”,“女”)】
  4. 日期、时间
    1. date
    2. time
    3. datetime

DDL操作

DDL: data definition languages. 数据表的创建删除修改,命令不区分大小写,貌似。

  • 查看表:

    • 查看当前数据库中的所有数据表:show tables

    • 查看某一个数据表的定义:desc tablename

    • 查看创建表的sql语句:show create table tablename \G。其中\G使记录按照字段竖向排列,其实也就是使输出内容更加简洁整齐。

      mysql> desc pages;
      +---------+----------------+------+-----+-------------------+----------------+
      | Field   | Type           | Null | Key | Default           | Extra          |
      +---------+----------------+------+-----+-------------------+----------------+
      | id      | bigint(7)      | NO   | PRI | NULL              | auto_increment |
      | tiltle  | varchar(200)   | YES  |     | NULL              |                |
      | content | varchar(10000) | YES  |     | NULL              |                |
      | created | timestamp      | NO   |     | CURRENT_TIMESTAMP |                |
      +---------+----------------+------+-----+-------------------+----------------+
      
      mysql> show create table pages \G;
      *************************** 1. row ***************************
             Table: pages
      Create Table: CREATE TABLE `pages` (
        `id` bigint(7) NOT NULL AUTO_INCREMENT,
        `tiltle` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
        `content` varchar(10000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
        `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
      ) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
      1 row in set (0.00 sec)
      
      ERROR:
      No query specified
      
  • 创建表:

    CREATE TABLE tablename(
    column_name_1 column_type_1 constraints,
    column_name_1 column_type_1 constraints,
    ......
    column_name_n column_type_n constraints,
    );
    
  • 删除表:DROP TABLE tablename

  • 修改表名:ALTER TABLE tablename RENAME [TO] new_tablename;

  • 修改表:

    • 修改表类型:ALTER TABLE tablename MODIFY [COLUMN] column_definition [FIRST | AFTER col_name],例如对pages这个数据表操作,改变content的类型,把varchar(10000)改成varchar(6000)。

      mysql> alter table pages modify content varchar(6000);
      Query OK, 72 rows affected (0.94 sec)
      Records: 72  Duplicates: 0  Warnings: 0
      
      mysql> desc pages;
      +---------+---------------+------+-----+-------------------+----------------+
      | Field   | Type          | Null | Key | Default           | Extra          |
      +---------+---------------+------+-----+-------------------+----------------+
      | id      | bigint(7)     | NO   | PRI | NULL              | auto_increment |
      | tiltle  | varchar(200)  | YES  |     | NULL              |                |
      | content | varchar(6000) | YES  |     | NULL              |                |
      | created | timestamp     | NO   |     | CURRENT_TIMESTAMP |                |
      +---------+---------------+------+-----+-------------------+----------------+
      4 rows in set (0.00 sec)        
      
    • 增加表字段,ALTER TABLE tablename ADD [column] column_definition [FIRST | AFTER col_name];

      mysql> alter table pages add column age int(3);
      Query OK, 0 rows affected (0.81 sec)
      Records: 0  Duplicates: 0  Warnings: 0
      
      mysql> desc pages;
      +---------+---------------+------+-----+-------------------+----------------+
      | Field   | Type          | Null | Key | Default           | Extra          |
      +---------+---------------+------+-----+-------------------+----------------+
      | id      | bigint(7)     | NO   | PRI | NULL              | auto_increment |
      | tiltle  | varchar(200)  | YES  |     | NULL              |                |
      | content | varchar(6000) | YES  |     | NULL              |                |
      | created | timestamp     | NO   |     | CURRENT_TIMESTAMP |                |
      | age     | int(3)        | YES  |     | NULL              |                |
      +---------+---------------+------+-----+-------------------+----------------+
      5 rows in set (0.00 sec)
      
    • 删除字段,ALTER TABLE tablename DROP [COLUMN] col_name;

    • 字段改名,ALTER TABLE tablename CHANGE [COLUMN] old_col_name column_definition [FIRST|AFTER col_name];

      mysql> ALTER TABLE pages CHANGE tiltle title varchar(100);
      Query OK, 72 rows affected (0.73 sec)
      Records: 72  Duplicates: 0  Warnings: 0
      
      mysql> desc pages;
      +---------+---------------+------+-----+-------------------+----------------+
      | Field   | Type          | Null | Key | Default           | Extra          |
      +---------+---------------+------+-----+-------------------+----------------+
      | id      | bigint(7)     | NO   | PRI | NULL              | auto_increment |
      | title   | varchar(100)  | YES  |     | NULL              |                |
      | content | varchar(6000) | YES  |     | NULL              |                |
      | created | timestamp     | NO   |     | CURRENT_TIMESTAMP |                |
      | age     | int(3)        | YES  |     | NULL              |                |
      +---------+---------------+------+-----+-------------------+----------------+
      5 rows in set (0.00 sec)
      

      注:change和modify都可以改变表的定义(数据类型),不同之处在于change需要写两次列名,可以同时更改列名;而modify只需要写一次列名,但不能更改列名。

    • 修改字段排列顺序。用可选项[FIRST|AFTER col_name]。比如把age放到最前。

      mysql> alter table pages modify age int(3) first;
      Query OK, 0 rows affected (0.64 sec)
      Records: 0  Duplicates: 0  Warnings: 0
      
      mysql> desc pages;
      +---------+---------------+------+-----+-------------------+----------------+
      | Field   | Type          | Null | Key | Default           | Extra          |
      +---------+---------------+------+-----+-------------------+----------------+
      | age     | int(3)        | YES  |     | NULL              |                |
      | id      | bigint(7)     | NO   | PRI | NULL              | auto_increment |
      | title   | varchar(100)  | YES  |     | NULL              |                |
      | content | varchar(6000) | YES  |     | NULL              |                |
      | created | timestamp     | NO   |     | CURRENT_TIMESTAMP |                |
      +---------+---------------+------+-----+-------------------+----------------+
      5 rows in set (0.00 sec)
      

DML语句

DML: data manipulation language. 数据库中表记录的插入(insert)更新(update)删除(delete)和查询(select)

  • 插入记录:INSERT INTO tablename (field1, field2, ... fieldn) VALUES(value1, value2, ... valuen);

    mysql> insert into pages (age,id,title) values(13, 12306, '第一条数据');
    Query OK, 1 row affected (0.05 sec)
    
    mysql> select * from pages;
    +------+-------+------------+---------+---------------------+
    | age  | id    | title      | content | created             |
    +------+-------+------------+---------+---------------------+
    |   13 | 12306 | 第一条数据 | NULL    | 2017-02-09 15:24:02 |
    +------+-------+------------+---------+---------------------+
    1 row in set (0.01 sec)
    

    添加多条数据

    INSERT INTO tablename (field1, field2, ... fieldn) 
    VALUES
    (record1_value1, record1_value2, ... record1_valuen),
    (record2_value1, record2_value2, ... record2_valuen),
    ...
    (recordn_value1, recordn_value2, ... recordn_valuen),
    ;
    
  • 更新记录:更改记录中的值,UPDATE tablename SET field1=value1, field2=value2,...,fieldn=valuen [WHERE CONDITION];

    mysql> update pages set content='第一条数据的内容blablabla' where id=12306;
    Query OK, 1 row affected (0.07 sec)
    Rows matched: 1  Changed: 1  Warnings: 0
    
    mysql> select * from pages;
    +------+-------+------------+---------------------------+---------------------+
    | age  | id    | title      | content                   | created             |
    +------+-------+------------+---------------------------+---------------------+
    |   13 | 12306 | 第一条数据 | 第一条数据的内容blablabla | 2017-02-09 15:24:02 |
    +------+-------+------------+---------------------------+---------------------+
    1 row in set (0.00 sec)
    

    可以对两个表同时操作,语法:UPDATE t1,t2,...,tn set t1.field1=expr1, tn.fieldn=exprn [WHERE CONDITION];。t1 t2是tablename。

    eg: update table1 a, table2 b set a.column1=a.colomn1*b.column2, b.column1=a.column2 where a.column3=b.column2;,这里的ab是别名。

  • 删除记录:DELETE FROM tablename [WHERE CONDITON];

    • 删除多个表里的数据:DELETE t1, t2,...,tn FROM t1, t2,...,tn [WHERE CONDITON];
    • 删除所有记录:DELETE FROM tablename; || TRUNCATE TABLE tablename,前者返回删除的记录数目,后者返回0。如果有自增项目,不希望删除后回到1的话,使用DELETE FROM tablename WHERE 1;
  • 查询记录:SELECT * FROM tablename [WHERE CONDITION];

    • 查询不重复记录【distinct】:select distinct column from tablename;
    • 条件查询【where】
    • 排序【order by】:select * from tablename [Where CONDITON] [ORDER BY field1 [DESC|ASC], field1 [DESC|ASC]];
    • 限制【limit】:select ... [LIMIT offset_start, raw_count],其中offset_start是其实偏移量,默认为0,raw_count是显示的行数。
    • 聚合:也就是分类汇总。
    • 表链接
    • 子查询:关键字包括innot in=!=existsnot exists

查询语句应该是MySQL中最复杂的了,之后再从新整理一份关于查询语句的笔记。

DCL语句

DCL: data control language. 主要是DBA用来管理系统中的对象权限时使用。

例,创建一个数据库用户chz,具有对scaping数据库中所有数据表的insert和select权限:

mysql> grant select, insert on scraping.* to 'chz'@'localhost' identified by '2333';
Query OK, 0 rows affected, 1 warning (0.12 sec)

之后退出root用户,用mysql -uchz -p2333登陆,就可以对scraping数据库进行操作了。

C:\Users\cc>mysql -uchz -p2333
mysql: [Warning] Using a password on the command line interface can be insecure.
......
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use scraping;
Database changed
mysql> insert into pages (age,id,title) values(14, 12307, '第二条数据');
Query OK, 1 row affected (0.05 sec)

mysql> select * from pages;
+------+-------+------------+---------------------------+---------------------+
| age  | id    | title      | content                   | created             |
+------+-------+------------+---------------------------+---------------------+
|   13 | 12306 | 第一条数据 | 第一条数据的内容blablabla | 2017-02-09 15:24:02 |
|   14 | 12307 | 第二条数据 | NULL                      | 2017-02-09 17:30:57 |
+------+-------+------------+---------------------------+---------------------+
2 rows in set (0.00 sec)

移除权限:登陆root用户,执行revoke insert on scraping.* from 'chz'@'localhost';,取消chz用户的insert权限。这时用chz登陆就只能进行select操作,而不能insert或者其他。

mysql> use scraping;
Database changed
mysql> insert into pages (age,id,title) values(14, 12308, '第san条数据');
ERROR 1142 (42000): INSERT command denied to user 'chz'@'localhost' for table 'pages'
mysql> delete from pages where id=12307;
ERROR 1142 (42000): DELETE command denied to user 'chz'@'localhost' for table 'pages'
mysql> select * from pages;
+------+-------+------------+---------------------------+---------------------+
| age  | id    | title      | content                   | created             |
+------+-------+------------+---------------------------+---------------------+
|   13 | 12306 | 第一条数据 | 第一条数据的内容blablabla | 2017-02-09 15:24:02 |
|   14 | 12307 | 第二条数据 | NULL                      | 2017-02-09 17:30:57 |
+------+-------+------------+---------------------------+---------------------+
2 rows in set (0.00 sec)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容