MySQL学习笔记-day03

唯一性约束修饰的字段具有唯一性,不能重复。但可以为NULL。

drop table if exists t_user;
create table t_user(
    id int,
    username varchar(255) unique
);
insert into t_user values(1,'zhangsan');
insert into t_user values(2,'zhangsan');
错误:ERROR 1062 (23000): Duplicate entry 'zhangsan' for key 'username'
insert into t_user(id) values(2);
insert into t_user(id) values(3);
insert into t_user(id) values(4);
drop table if exists t_user;
create table t_user(
    id int,
    usercode varchar(255),
    username varchar(255),
    unique(usercode,username) //多个字段联合添加约束
);
insert into t_user values(1,'111','zs');
insert into t_user values(2,'111','ls');
insert into t_user values(3,'222','zs');
select * from t_user;
    +------+----------+----------+
    | id   | usercode | username |
    +------+----------+----------+
    |    1 | 111      | zs       |
    |    2 | 111      | ls       |
    |    3 | 222      | zs       |
    +------+----------+----------+
insert into t_user values(4,'111','zs');
错误:ERROR 1062 (23000): Duplicate entry '111-zs' for key 'usercode'
drop table if exists t_user;
create table t_user(
    id int,
    usercode varchar(255) unique,
    username varchar(255) unique
);
insert into t_user values(1,'111','zs');
insert into t_user values(2,'111','ls');
错误:ERROR 1062 (23000): Duplicate entry '111' for key 'usercode'
select * from t_user;
     +------+----------+----------+
     | id   | usercode | username |
     +------+----------+----------+
     |    1 | 111      | zs       |
     +------+----------+----------+
注意:not null只有列级约束,没有表集约束。
drop table if exists t_user;
create table t_user(
    id int primary key, # 列级约束
    username varchar(255),
    email varchar(255)
);
insert into t_user(id,username,email) values(2,'ls','ls@123.com');
insert into t_user(id,username,email) values(3,'ww','ww@123.com');
select * from t_user;
    +----+----------+------------+
    | id | username | email      |
    +----+----------+------------+
    |  1 | zs       | zs@123.com |
    |  2 | ls       | ls@123.com |
    |  3 | ww       | ww@123.com |
    +----+----------+------------+
不能重复
insert into t_user(id,username,email) values(1,'jack','jack@123.com');
错误:ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

不能为空
insert into t_user(username,email) values('jack','jack@123.com');
错误:ERROR 1364 (HY000): Field 'id' doesn't have a default value

根据以上的测试得出:id是主键,因为添加了主键约束,主键字段中的数据不能为NULL,也不能重复。

主键的特点:不能为NULL,也不能重复。

主键约束: primary key

主键字段:id字段添加primary key之后,id叫做主键字段。

主键值:id字段中的每一个值都是主键值。

  • 表格设计的三种范式都有要求,第一种范式要求任何表格都要有主键。
    [En]

    there are requirements in the three paradigms of table design, and the first paradigm requires that any table should have a primary key.*

  • 主键的作用:主键值是该表中记录的该行的唯一标识。(就像一个人的身份证)
    [En]

    the role of the primary key: the primary key value is the only identification of this row recorded in this table. (like a person’s ID card)*

根据主键字段中的字段数划分:

[En]

Divided according to the number of fields in the primary key field:

单一主键(建议的,常用的。)

复合主键(多个字段联合起来添加一个主键约束。不建议使用)

根据主键性质来划分:

自然主键:主键值最好是与业务无关的自然数。建议使用此方法。)

[En]

Natural primary key: the primary key value is preferably a natural number that has nothing to do with the business. This method is recommended.)

业务主键:主键值与系统的业务关联,如以银行卡卡号为主键,以身份证号为主键。(不推荐)

[En]

Business primary key: the primary key value is linked to the business of the system, for example, holding the card number of the bank card as the primary key and the ID card number as the primary key. (not recommended)

最好不要将链接到业务的字段作为主键。因为将来一旦业务发生变化,主键值可能也需要改变,但有时没有办法改变,因为改变可能会导致重复的主键值。

[En]

It is best not to take the fields linked to the business as the primary key. Because once the business changes in the future, the primary key value may also need to change, but sometimes there is no way to change, because the change may lead to duplicate primary key values.

一张表的主键约束只能有一个

drop table if exists t_user;
create table t_user(
    id int,
    username varchar(255),
    primary key(id)
);
insert into t_user(id,username) values(1,'zs');
insert into t_user(id,username) values(2,'ls');
insert into t_user(id,username) values(3,'ws');
insert into t_user(id,username) values(4,'cs');
select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    |  2 | ls       |
    |  3 | ws       |
    |  4 | cs       |
    +----+----------+
drop table if exists t_user;
create table t_user(
    id int primary key auto_increment,  //id字段自动维护一个自增数字,从1开始,以1递增。
    username varchar(255)
);
insert into t_user(username) values('a');
insert into t_user(username) values('b');
insert into t_user(username) values('c');
insert into t_user(username) values('d');
insert into t_user(username) values('e');
insert into t_user(username) values('f');
select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | a        |
    |  2 | b        |
    |  3 | c        |
    |  4 | d        |
    |  5 | e        |
    |  6 | f        |
    +----+----------+

提示:Oracle当中也提供了一个自增机制,叫做:序列(sequence)对象。

外键约束: foreign key

外键字段:添加具有外键约束的字段

[En]

Foreign key fields: adding fields with foreign key constraints

外键值:外键字段中的每个值

[En]

Foreign key value: each value in the foreign key field

业务背景:请设计数据库表来维护学生和班级信息

[En]

Business background: please design database tables to maintain information about students and classes

第一种方案:一个表存储所有数据。

[En]

The first scheme: one table stores all the data.

缺点:冗余。[不推荐]如果学生属于同一个班级,他们的班号和班名是相同的。要修改一个类,需要修改很多行。

[En]

Disadvantages: redundancy. [not recommended] if students belong to the same class, their class number and class name are the same. To modify a class, you need to modify a lot of lines.

第二种方案:两种表(学生表和班级表) 每一种数据,使用一个表来存储。

t_class 班级表————父表

cno(pk)     cname
1           zhangsan    101
2           lisi        101
3           wangwu      101
4           zhaoliu     102
5           tangqi      102

写出上表的造表语句:

[En]

Write out the table-building statements of the above table:

t_student 学生表中的classno字段引用t_class 班级表中的cno字段,此时t_student表叫做子表。t_class表叫做父表。

顺序要求:
删除数据时,先删除子表,再删除父表。

[En]

When deleting data, delete the child table first, and then delete the parent table.

添加数据时,首先添加父表,然后添加子表。

[En]

When adding data, first add the parent table, and then add the child table.

创建表时,请先创建父表,然后再创建子表。

[En]

When creating a table, create the parent table first, and then create the child table.

删除表时,请先删除子表,然后删除父表。

[En]

When you delete a table, delete the child table first, then the parent table.

drop table if exists t_student;
drop table if exists t_class;
create table t_class(
    cno int,
    cname varchar(255),
    primary key(cno)
);
create table t_student(
    sno int,
    sname varchar(255),
    classno int,
    primary key(sno),
    foreign key(classno) references t_class(cno)
);

insert into t_class values(101,'xxx');
insert into t_class values(102,'yyy');

insert into t_student values(1,'zs',101);
insert into t_student values(2,'ls',101);
insert into t_student values(3,'wu',102);
insert into t_student values(4,'zl',102);
insert into t_student values(5,'tq',102);

select * from t_class;
select * from t_student;

insert into t_student values(6,'zh',103);
错误:ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (bjpowernode.t_student,CONSTRAINT t_student_ibfk_1 FOREIGN KEY (classno) REFERENCES t_class (cno))

外键值可以为NULL。

insert into t_student(sno,sname) values(6,'sl');
select * from t_student;
    +------+-------+---------+
    | sno  | sname | classno |
    +------+-------+---------+
    |    1 | zs    |     101 |
    |    2 | ls    |     101 |
    |    3 | wu    |     102 |
    |    4 | zl    |     102 |
    |    5 | tq    |     102 |
    |    6 | sl    |    NULL |
    +------+-------+---------+

不是的。它不一定是主键,但必须是唯一的。

[En]

No. It is not necessarily a primary key, but it must be unique.

mysql默认使用的存储引擎是InnoDB方式。默认采用的字符集是UTF-8。

  • 数据库中的各表均被(在创建表时)指定的存储引擎来处理。
  • 服务器可用的引擎取决于以下因素:
    [En]

    the engines available to the server depend on the following factors:*

  • MySQL的版本
  • 服务器在开发时如何被配置
  • 启动选项:为了解当前服务器中有哪些存储引擎可用,可使用SHOW ENGINES语句;(末尾加”\G”可以让结果显示更加易读)

存储引擎这个名字只有在mysql中存在。(Oracle中有对应的机制,但不叫存储引擎。Oracle中没有特殊的名字,就是”表的存储方式”。)

mysql支持很多存储引擎,每一种存储引擎都对应了一种不同的存储方式。

show engines \G;
Engine: MyISAM
         Support: YES
         Comment: MyISAM storage engine
    Transactions: NO    // 不支持事务
          XA: NO
      Savepoints: NO

MyISAM这种存储引擎不支持事务。

它管理的表具有以下特征:

[En]

The tables it manages have the following characteristics:

  • 使用三个文件表示每个表:
    [En]

    use three files to represent each table:*

  • 格式文件 —— 存储表结构的定义(mytable.frm)
  • 数据文件 —— 存储表行的内容(mytable.MYD)
  • 索引文件 —— 存储表上索引(mytable.MYI)
  • 灵活的 ATUO_INCREMENT字段处理。
  • 可转换为压缩的只读表格以节省空间。
    [En]

    can be converted to compressed, read-only tables to save space.*

优点:可压缩,节省存储空间。并且可以将其转换为只读表,以提高检索效率。

[En]

Advantages: can be compressed to save storage space. And it can be converted into a read-only table to improve the efficiency of retrieval.

缺点:不支持事务。

Engine: InnoDB
         Support: DEFAULT
         Comment: Supports transactions, row-level locking, and foreign keys
    Transactions: YES
          XA: YES   //支持事务
      Savepoints: YES

它管理的表具有以下主要特征:

[En]

The tables it manages have the following main characteristics:

  • 每个InnoDB表在数据库目录中以 .frm格式文件表示
  • InnoDB表空间tablespace被用于存储表的内容(tablespace只是一个逻辑概念)
  • 提供一套记录交易活动的日志文件
    [En]

    provide a set of log files to record transactional activities*

  • COMMIT(提交)SAVEPOINTROLLBACK(回滚)支持事务处理
  • 提供全ACID兼容,ACID事务具有的四个特征
  • 在MySQL服务器崩溃后提供自动恢复机制
  • 多版本(MVCC)和行级锁定
  • 支持外键和引用的完整性,包括级联删除和更新
    [En]

    support the integrity of foreign keys and references, including cascading deletions and updates*

表的结构存储在 xxx.frm文件中
数据存储在tablespace这样的表空间中

优点:支持事务、行级锁、外键等。这种存储引擎数据的安全性是有保证的。

[En]

Advantages: support transactions, row-level locks, foreign keys and so on. The security of this kind of storage engine data is guaranteed.

缺点:(数据存储在tablespace这样的表空间中)无法被压缩,无法转换成只读。

Engine: MEMORY
         Support: YES
         Comment: Hash based, stored in memory, useful for temporary tables
    Transactions: NO
          XA: NO //不支持事务
      Savepoints: NO

MEMORY存储引擎管理的表具有下列特征:

  • 在数据库目录内,每个表均以 .frm格式的文件表示。
  • 表数据和索引存储在内存中。
    [En]

    Table data and indexes are stored in memory.*

  • 表级锁机制。
  • 不能包含 TEXT或者 BLOB字段。

使用MEMORY存储引擎的表,其数据存储在内存中,且行的长度固定,这两个特点使得MEMORY存储引擎非常快。

优点:查询速度最快。

缺点:不支持事务。数据容易丢失。因为所有数据和索引都是存储在内存当中的,断电就没。以前叫做HEPA引擎。

  • MyISAM表最合适于大量的数据读而少量数据更新的混合操作。MyISAM表的另一种适用场景是使用压缩的只读表。
  • 如果查询中包含较多的数据更新,应使用InnoDB。其行级锁机制和多版本的支持为数据读取和更新的混合操作提供了良好的并发机制。
  • 可使用MEMORY存储引擎来存储非永久需要的数据,或者是能够从基于磁盘的表中重新生成的数据。

交易是一个完整的业务逻辑单元,不能再分割。

[En]

A transaction is a complete business logic unit, which can no longer be divided.

比如:银行账户转账,从A账户向B账户转账10000。需要执行两条update语句:

update t_act set balance = blance - 10000 where actno = 'act-001';
update t_act set balance = blance + 10000 where actno = 'act-002';

以上两条DML语句必须同时成功,或者同时失败,不允许出现一条成功,一条失败。

要想保证以上两条DML语句同时成功,或者同时失败,那么就需要使用数据库的”事务机制”。

为什么?

因为这三条语句与数据库表中的“data”相关。

[En]

Because these three statements are related to the “data” in the database table.

交易的存在是为了保证数据的完整性和安全性。

[En]

The existence of transaction is to ensure the integrity and security of data.

所有的业务都能使用1条DML语句搞定就不需要事务了。但实际情况不是这样的,通常一个”事儿(事务【业务】)”需要多条DML语句共同联合完成。

事务包括四大特性:ACID

A:原子性:事务是最小的工作单元,不可再分。
C:一致性:事务必须保证多条DML语句同时成功或者同时失败。
I:隔离性:事务A和事务B之间具有隔离。
D:持久性:持久性说的是最终数据必须持久化到硬盘文件中,事务才算成功的结束。

隔离是指当多个用户的并发事务访问同一数据库时,一个用户的事务不应被其他用户的事务干扰,多个并发事务应相互隔离。

[En]

Isolation means that when multiple users’ concurrent transactions access the same database, one user’s transactions should not be disturbed by other users’ transactions, and multiple concurrent transactions should be isolated from each other.

有用于事务隔离的隔离级别,理论上包括四个:

[En]

There are isolation levels for transaction isolation, which theoretically include four:

对方的交易尚未提交,我们当前的交易可以读取对方的未提交数据。

[En]

The other party’s transaction has not been committed yet, and our current transaction can read the other party’s uncommitted data.

这种程度的隔离解决了肮脏阅读的问题。

[En]

This level of isolation solves the problem of dirty reading.

我们可以在提交对方的交易后读取数据。

[En]

We can read the data after the transaction of the other party is submitted.

提交阅读的问题是它不能重复阅读。

[En]

The problem with reading submitted is that it cannot be read repeatedly.

这种隔离级别解决了不可重复读取的问题。

[En]

This isolation level solves the problem of non-repeatable reading.

可重复可读性的问题:读取的数据是一种错觉。

[En]

The problem with repeatable readability: the data read is an illusion.

解决了所有问题。

效率低下。交易需要排队。一致性最好、性能最差的那个。

[En]

Inefficient. Transactions need to be queued. The one with the best consistency and the worst performance.

Oracle数据库默认的隔离级别是:读已提交。

mysql数据库默认的隔离级别是:可重复读。

mysql事务默认情况下是自动提交的。(什么是自动提交?只要执行任意一条DML语句,则提交一次。)

怎么关闭自动提交? ———— start transaction;

drop table if exists t_user;
create table t_user(
    id int primary key auto_increment,
    username varchar(255)
);
insert into t_user(username) values('zs');

select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    +----+----------+

rollback;

select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    +----+----------+

演示:使用 start transaction;关闭自动提交机制。

start transaction;

insert into t_user(username) values('lisi');

select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    |  2 | lisi     |
    +----+----------+

insert into t_user(username) values('wangwu');

select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    |  2 | lisi     |
    |  3 | wangwu   |
    +----+----------+

rollback;

select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    +----+----------+
mysql> start transaction;
    Query OK, 0 rows affected (0.00 sec)

    mysql> insert into t_user(username) values('wangwu');
    Query OK, 1 row affected (0.00 sec)

    mysql> insert into t_user(username) values('rose');
    Query OK, 1 row affected (0.00 sec)

    mysql> insert into t_user(username) values('jack');
    Query OK, 1 row affected (0.00 sec)

    mysql> select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    |  4 | wangwu   |
    |  5 | rose     |
    |  6 | jack     |
    +----+----------+
    4 rows in set (0.00 sec)

    mysql> commit;
    Query OK, 0 rows affected (0.00 sec)

    mysql> select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    |  4 | wangwu   |
    |  5 | rose     |
    |  6 | jack     |
    +----+----------+
    4 rows in set (0.00 sec)

    mysql> rollback;
    Query OK, 0 rows affected (0.00 sec)

    mysql> select * from t_user;
    +----+----------+
    | id | username |
    +----+----------+
    |  1 | zs       |
    |  4 | wangwu   |
    |  5 | rose     |
    |  6 | jack     |
    +----+----------+
    4 rows in set (0.00 sec)

第一:演示第一级别:读未提交read uncommitted

设置事务的全局隔离级别:

[En]

Set the global isolation level for the transaction:

set global transaction isolation level read uncommitted;

查看事务处理的全局隔离级别:

[En]

View the global isolation level of the transaction:

select @@global.tx_isolation;
        +-----------------------+
        | @@global.tx_isolation |
        +-----------------------+
        | READ-UNCOMMITTED      |
        +-----------------------+

第二:演示read committed

set global transaction isolation level read committed;

第三:演示repeatable read

set global transaction isolation level repeatable read;

第四:演示serializable

set global transaction isolation level serializable;

mysql远程登录: mysql -h192.168.151.18 -uroot -p123

索引相当于一本书的目录,通过它可以快速找到相应的资源。

[En]

The index is equivalent to the catalogue of a book, through which the corresponding resources can be found quickly.

在数据库端,有两种查询表的方法:

[En]

On the database side, there are two ways to query a table:

第一种方式:全表扫描

第二种方式:根据索引进行检索(非常高效)

[En]

The second way: retrieve according to the index (very efficient)

事实上,最根本的原则是缩小扫描范围。

[En]

In fact, the most fundamental principle is to narrow the scope of scanning.

虽然索引可以提高检索效率,但不能随意添加,因为索引也是数据库中的对象,还需要对数据库进行持续维护。这里面有维护费用。例如,表中的数据通常

[En]

Although the index can improve the retrieval efficiency, it can not be added at will, because the index is also an object in the database, and it also needs continuous maintenance of the database. There are maintenance costs. For example, the data in a table often

被修改,所以不适合添加索引,因为一旦数据被修改,就需要对索引进行重新排序和维护。

[En]

Is modified, so it is not appropriate to add an index, because once the data is modified, the index needs to be reordered and maintained.

索引被用来快速找出在一个列上用一特定值的行。没有索引,MySQL不得不首先以第一条记录开始,然后读完整个表直到它找出相关的行。表越大,花费时间越

多。对于一个有序字段,可以运用二分查找(Binary Search),这就是为什么性能能得到本质上的提高。

MYISAM和InnoDB都是B+Tree作为索引结构。
(主键:unique都会默认的添加索引)

添加索引就是将索引添加到一个字段或某些字段。

[En]

To add an index is to add an index to a field, or some fields.

select ename,sal from emp where ename = 'SIMITH';

当ename字段上没有添加索引的时候,以上sql语句会进行全表扫描,扫描ename字段中所有的值。

当ename字段上添加索引的时候,以上sql语句会根据索引扫描,快速定位。

create index 索引名称 on 表名(字段名);
drop index 索引名称 on 表名;
  • 数据量庞大。(根据客户的需求,根据线上的环境)
  • 该字段很少的DML操作。(因为字段进行修改操作,索引也需要维护)
  • 该字段经常出现在where子句中。(经常根据哪个字段查询)

根据主键查询效率更高。试着根据主键进行搜索。

[En]

It is more efficient to query according to the primary key. Try to search according to the primary key.

explain select ename,job from emp where sal = 5000;
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra       |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
|  1 | SIMPLE      | emp   | ALL  | NULL          | NULL | NULL    | NULL |   14 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+

explain主要用于分析查询语句或表结构的性能瓶颈。

通过 explain+sql语句可以知道如下内容:

①表的读取顺序。(对应id)

②数据读取操作的操作类型。(对应select_type)

③哪些索引可以使用。(对应possible_keys)

④哪些索引被实际使用。(对应key)

⑤表直接的引用。(对应ref)

⑥每张表有多少行被优化器查询。(对应rows)

explain select ename,job,sal from emp where sal > 1500 group by sal;
+----+-------------+-------+------+---------------+------+---------+------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra                                        |
+----+-------------+-------+------+---------------+------+---------+------+------+----------------------------------------------+
|  1 | SIMPLE      | emp   | ALL  | NULL          | NULL | NULL    | NULL |   14 | Using where; Using temporary; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+------+----------------------------------------------+

给薪资sal字段添加索引:

create index emp_sal_index on emp(sal);
explain select ename,job from emp where sal = 5000;
+----+-------------+-------+------+---------------+---------------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key           | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+---------------+---------------+---------+-------+------+-------------+
|  1 | SIMPLE      | emp   | ref  | emp_sal_index | emp_sal_index | 9       | const |    1 | Using where |
+----+-------------+-------+------+---------------+---------------+---------+-------+------+-------------+

通过B Tree缩小扫描范围,底层索引进行了排序,分区,索引会携带数据在表中的”物理地址”,最终通过索引检索到数据之后,获取到关联的物理地址,通过物理

地址位置表中的数据效率最高。

[En]

The data in the address location table is the most efficient.

create index emp_ename_index on emp(ename);
select ename from emp where ename = 'SIMITH';

通过索引转换为:

select ename from emp where 物理地址 = 0x3;

单个索引:向单个字段添加索引

[En]

Single index: adding an index to a single field

综合索引:将1个索引加到多个字段中

[En]

Composite index: add 1 index to multiple fields together

主键索引:索引自动添加到主键

[En]

Primary key index: an index is automatically added to the primary key

唯一索引:有unique约束的字段上会自动添加索引

模糊查询like。

查询ename字段中包含有”A”的。

create index emp_ename_index on emp(ename);
select ename from emp where ename like '%A%';

模糊查询的时候,第一个通配符使用的是 %,这个时候索引是失效的,会进行全表扫描。

模糊查询时,第一个位置最好不要写%!

从不同的角度来看待这些数据。同一张表的数据是从不同的角度查看的。)

[En]

Look at the data from a different perspective. The data of the same table are viewed from different angles.)

  • 视图是一种根据查询(也就是SELECT表达式)定义的数据库对象,用于获取想要看到和使用的局部数据。
  • 视图有时也被称为”虚拟表”。
  • 视图可以被用来从常规表(称为”基表”)或其他视图中查询数据。
  • 与直接从基表获取数据相比,视图具有以下优势:
    [En]

    views have the following advantages over getting data directly from the base table:*

  • 访问数据变的简单
  • 可被用来对不同用户显示不同的表的内容。
    • 用来协助适配表的结构以适应前端现有的应用程序
    • 视图作用:
    • 提高检索效率
    • 隐藏表的实现细节【面向视图检索】
create view myview as select empno,ename from emp;drop view myview;

注意:只有DQL语句才能以视图对象的方式创建出来。

可以对视图进行CRUD操作。

(create view myview as select empno,ename from emp;)
select * from myview;
    +-------+--------+
    | empno | ename  |
    +-------+--------+
    |  7369 | SIMITH |
    |  7499 | ALLEN  |
    |  7521 | WARD   |
    |  7566 | JONES  |
    |  7654 | MARTIN |
    |  7698 | BLAKE  |
    |  7782 | CLARK  |
    |  7788 | SCOTT  |
    |  7839 | KING   |
    |  7844 | TURNER |
    |  7876 | ADAMS  |
    |  7900 | JAMES  |
    |  7902 | FORD   |
    |  7934 | MILLER |
    +-------+--------+
create table emp_bak as select * from emp;# 复制表结构及数据到新表emp_bak。
create view myview1 as select empno,ename,sal from emp_bak;# 通过原表emp_bak,创建视图myview1。
update myview1 set ename = 'hehe',sal = 1 where empno = 7369;# 通过视图修改原表数据。
delete from myview1 where empno = 7369;# 通过视图删除原表数据。

视图可以隐藏表的实现细节。保密级别较高的系统,数据库只对外提供相关的视图,java程序员只对视图对象进行CRUD。视图并不会提高查询效率。

create view myview2 as select empno a,ename b,sal c from emp_bak;# 创建视图
select * from myview2;
    +------+--------+---------+
    | a    | b      | c       |
    +------+--------+---------+
    | 7499 | ALLEN  | 1600.00 |
    | 7521 | WARD   | 1250.00 |
    | 7566 | JONES  | 2975.00 |
    | 7654 | MARTIN | 1250.00 |
    | 7698 | BLAKE  | 2850.00 |
    | 7782 | CLARK  | 2450.00 |
    | 7788 | SCOTT  | 3000.00 |
    | 7839 | KING   | 5000.00 |
    | 7844 | TURNER | 1500.00 |
    | 7876 | ADAMS  | 1100.00 |
    | 7900 | JAMES  |  950.00 |
    | 7902 | FORD   | 3000.00 |
    | 7934 | MILLER | 1300.00 |
    +------+--------+---------+
insert into myview2(a,b,c) values(8000,'GOD',9999);# 插入数据
select * from myview2;
    +------+--------+---------+
    | a    | b      | c       |
    +------+--------+---------+
    | 7499 | ALLEN  | 1600.00 |
    | 7521 | WARD   | 1250.00 |
    | 7566 | JONES  | 2975.00 |
    | 7654 | MARTIN | 1250.00 |
    | 7698 | BLAKE  | 2850.00 |
    | 7782 | CLARK  | 2450.00 |
    | 7788 | SCOTT  | 3000.00 |
    | 7839 | KING   | 5000.00 |
    | 7844 | TURNER | 1500.00 |
    | 7876 | ADAMS  | 1100.00 |
    | 7900 | JAMES  |  950.00 |
    | 7902 | FORD   | 3000.00 |
    | 7934 | MILLER | 1300.00 |
    | 8000 | GOD    | 9999.00 |
    +------+--------+---------+
    select * from emp_bak;# 视图myview2对应的原表emp_bak
    +-------+--------+-----------+------+------------+---------+---------+--------+
    | empno | ename  | job       | mgr  | hiredate   | sal     | comm    | deptno |
    +-------+--------+-----------+------+------------+---------+---------+--------+
    |  7499 | ALLEN  | SALESMAN  | 7698 | 1981-02-20 | 1600.00 |  300.00 |     30 |
    |  7521 | WARD   | SALESMAN  | 7698 | 1981-02-22 | 1250.00 |  500.00 |     30 |
    |  7566 | JONES  | MANAGER   | 7839 | 1981-04-02 | 2975.00 |    NULL |     20 |
    |  7654 | MARTIN | SALESMAN  | 7698 | 1981-09-28 | 1250.00 | 1400.00 |     30 |
    |  7698 | BLAKE  | MANAGER   | 7839 | 1981-05-01 | 2850.00 |    NULL |     30 |
    |  7782 | CLARK  | MANAGER   | 7839 | 1981-06-09 | 2450.00 |    NULL |     10 |
    |  7788 | SCOTT  | ANALYST   | 7566 | 1987-04-19 | 3000.00 |    NULL |     20 |
    |  7839 | KING   | PRESIDENT | NULL | 1981-11-17 | 5000.00 |    NULL |     10 |
    |  7844 | TURNER | SALESMAN  | 7698 | 1981-09-08 | 1500.00 |    NULL |     30 |
    |  7876 | ADAMS  | CLERK     | 7788 | 1987-05-23 | 1100.00 |    NULL |     20 |
    |  7900 | JAMES  | CLERK     | 7698 | 1981-12-03 |  950.00 |    NULL |     30 |
    |  7902 | FORD   | ANALYST   | 7566 | 1981-12-03 | 3000.00 |    NULL |     20 |
    |  7934 | MILLER | CLERK     | 7782 | 1982-01-23 | 1300.00 |    NULL |     10 |
    |  8000 | GOD    | NULL      | NULL | NULL       | 9999.00 |    NULL |   NULL |
    +-------+--------+-----------+------+------------+---------+---------+--------+
create user username identified by 'password';

说明:username————你将创建的用户名,password————该用户的登录密码。如果为空,则该用户不需要密码登录服务器。

grant all privileges on dbname.tbname to 'username'@'login ip' identified by 'password' with grant option;

首先以root用户进入mysql,然后键入命令: grant select,insert,update,delect on *.* to p361 @localhost identified by "123";如果希望该用户能够在任何机器上登录mysql,则将 localhost改为” %“;

我们测试用户一般使用该命令授权, grant all privileges *.* to 'p3610'@'%' identified by "123";

注意:使用上述命令授权的用户不能授权其他用户。如果希望此用户授权,请使用以下命令:

[En]

Note: a user authorized with the above command cannot authorize another user. If you want this user to authorize, use the following command:

grant privileges on databasename.tablename to 'mysql_user_name'@'host' with grant option;
revoke privileges on dbname[.tbname] from username;
revoke privileges on *.* from p361;

进入mysql库中

use mysql;
select * from user;
update user set password = password('qwe') where user = 'p646';
flush privileges;

在windows的dos命令窗口(不要登录到mysql系统当中)中执行: mysqldump bjpowernonde>D:\bjpowernode.sql -uroot -p123;

在windows的dos命令窗口中执行: mysqldump bjpowernode>D:\bjpowernode.sql -uroot -proot;

登录MySQL数据库管理系统之后,

create database bjpowernode;
use bjpowernode;

执行:

source D:\bjpowernode.sql;

这是设计表格的基础。按照这三个范例设计的表格将不会有数据冗余。

[En]

The basis for designing the table. Tables designed according to this three paradigms will not have data redundancy.

第一个范型:任何表都应该有一个范型,每个字段的原子性不能再分开。

[En]

The first paradigm: any table should have a paradigm one, and the atomicity of each field can no longer be separated.

数据库表中不能有重复的记录,每个字段都是原子的,不能分割。

[En]

There can be no duplicate records in the database table, and each field is atomic and cannot be divided.

对于第一个范例,每行必须是唯一的,即每个表必须有一个主键,这是我们数据库设计的最基本要求。

[En]

With regard to the first paradigm, each row must be unique, that is, each table must have a primary key, which is the most basic requirement of our database design.

第二个范例:基于第一个范例,所有非主键字段都被要求完全依赖于主键,不能产生部分依赖。

[En]

The second paradigm: based on the first paradigm, all non-primary key fields are required to rely entirely on the primary key and cannot produce partial dependencies.

多人对多人?三个表,关系表中的两个外键。

[En]

Many to many? Three tables, two foreign keys in the relational table.

t_student学生表
sno(pk)     sname
1       王老师
2       张老师
3       李老师
t_student_teacher_relation学生教师关系表
id(pk)      sno(fk)     tno(fk)
1       班级1
2       班级2
学生t_student
sno(pk) sname       classno(fk)
1       zs      123
2       ls      456
t_user_detail   用户详细信息表
id(pk+fk)       realname    tel ...

1       张三      12345678901 1
2       李四      09876543211 2
  1. IGNORE:有则忽略,无则插入

  2. REPLACE:有则删除再插入,无则插入

  3. ON DUPLIACATE KEY UPDATE:有则更新,无则插入

Original: https://www.cnblogs.com/zhllw/p/16172787.html
Author: 学者莱维
Title: MySQL学习笔记-day03

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/505466/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 设计模式之简单工厂

    一、简单工厂:为了客户类和服务类之间的解耦,把对象的创建任务交给第三方类,这个第三方类就充当工厂的作用,严格来说简单工厂不属于23种设计模式之一。 二、实现思路 :创建一个简单工厂…

    数据库 2023年6月14日
    071
  • MySQL在Linux环境下的安装、初始化、配置

    CentOS操作系统,可选择: MySQL Community Server 8.0.28 Red Hat Enterprise Linux / Oracle Linux Red …

    数据库 2023年5月24日
    081
  • update更新很慢(字段类型引发)

    开发人员在sql审核平台提交了2000多条update语句,每条语句只更新一条,where条件由索引,在sql审核平台在测试执行阶段已经执行了20多分钟。于是让看一下数据库后台线程…

    数据库 2023年6月16日
    0102
  • B树-查找

    B树系列文章 1. B树-介绍 2. B树-查找 3. B树-插入 4. B树-删除 查找 假设有一棵3阶B树,如下图所示。 下面说明在该B树中查找 52的过程 首先,从根结点出发…

    数据库 2023年6月14日
    0128
  • mysql8主从配置

    一、一般配置主从(这里主是m3300,从是3301、3302) 1.配置m3301 从mysql8里拿出这两个文件到m3301 2.配置my.ini 初&am…

    数据库 2023年5月24日
    073
  • 【转】Windows安装运行Kafka

    一、安装JAVA JDK 1、下载安装包 注意:根据32/64位操作系统下载对应的安装包 2、添加系统变量:JAVA_HOME=C:\Program Files (x86)\Jav…

    数据库 2023年6月6日
    059
  • 通过VS下载的NuGet包,如何修改其下载存放路径?

    我们通过NuGet包管理器下载的引用包,默认是存放在C盘的,存储路径一般是: C:\Users\{系统用&…

    数据库 2023年6月14日
    0177
  • 如何设计一个更通用的查询接口

    临近放假,手头的事情没那么多,老是摸鱼也不好,还是写写博客吧。 今天来聊聊: 如何设计一个通用的查询接口。 首先,我们从一个简单的场景开始。现在,我需要一个订单列表,用来查询【我的…

    数据库 2023年6月6日
    091
  • 国行XBoxOne第一次开机配置主要问题备忘

    1,Kinect可以在设置中关闭。 2,彻底关闭主机,需要长按主机上的开关键,将主机彻底关机,同时开机只要轻触一下主机开关机键即可 3,不能更新问题:3.1检查网络已连接3.2检查…

    数据库 2023年6月14日
    0225
  • MySQL实战45讲 13

    13 | 为什么表数据删掉一半,表文件大小不变? 一个 InnoDB 表包含两部分,即: 表结构定义和 数据。 在 MySQL 8.0 版本以前, 表结构是存在以.frm 为后缀的…

    数据库 2023年6月16日
    081
  • UniApp文件上传(SpringBoot+Minio)

    UniApp文件上传(SpringBoot+Minio) 一、Uni文件上传 (1)、文件上传的问题 UniApp文件上传文档 uni.uploadFile({ url: ‘htt…

    数据库 2023年6月6日
    080
  • Java 考试系统项目源码 springboot mybaits vue.js 支持手机端考试

    新增功能:培训学习模块, PDF电子课程、视频课程、直播课程(自己搭建直播流服务器) 人脸识别(考试时验证,有开关)、补考开关 组建试卷:创建试卷,题目、类型、总分、及格分数、时长…

    数据库 2023年6月6日
    070
  • 三分钟图解事务隔离级别,看一遍就懂

    前文说过,”锁” 是数据库系统区别于文件系统的一个关键特性,其对象是 事务,用来锁定的是数据库中的对象,如表、页、行等。锁确实提高了并发性,但是却不可避免地…

    数据库 2023年5月24日
    0103
  • MySQL实战45讲 3

    03 | 事务隔离:为什么你改了我还看不见? 事务 Transaction TRX 事务就是 要保证一组数据库操作,要么全部成功,要么全部失败。 MySQL 原生的 MyISAM …

    数据库 2023年6月16日
    074
  • Oracle扩展表空间

    Oracle扩展表空间 前言: Oracle表空间扩展最大为32G,目前我还未找到可以打破限制的办法。 一、查看表空间信息和使用情况 查看表空间的名字及文件所在位置 — &amp…

    数据库 2023年6月16日
    090
  • 多商户商城系统功能拆解24讲-平台端分销会员

    多商户商城系统,也称为B2B2C(BBC)平台电商模式多商家商城系统。可以快速帮助企业搭建类似拼多多/京东/天猫/淘宝的综合商城。 多商户商城系统支持商家入驻加盟,同时满足平台自营…

    数据库 2023年6月14日
    084
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球