---
title: "数据库相关理解"
author: "Menuz"
date: "2012-11-04T16:41:59Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2012-11-04T16:46:09Z"
id: 1715301
url: "https://menuz.iteye.com/blog/1715301"
---

**1:N,N:1和N:M**
**1:N** means one to many, Like an author has many books
**N:1** means many to one, Like there are many line items on a single purchase order 
**N:M** means many to many, Like a magazine company sells many different magazine title to many customers 

1:N 1:N数据库中有两种建表方式：
**1)**

```sql

create table tb_author {
	a_id int primary key auto_increment not null,
	a_name varchar(20) not null
}

```



```sql

create table tb_book {
	b_id int primary key auto_increment not null,
	b_name varchar(30) not null，
	a_id int not null
}

```

这里假设book只有一个作者。非1的实体表中要引用1实体。
例:
一个中国有24个省，浙江省有xxx个市，这种关系很明确采用1），而1）例子
中的书作者现实一般有若干，不可能只有一个，所以明确实体之间关系很重要。

**2)**

```sql

create table tb_author {
	a_id int primary key auto_increment not null,
	a_name varchar(20) not null
}
```



```sql
create table tb_book {
	b_id int primary key auto_increment not null,
	b_name varchar(30) not null
}
```



```sql
create table tb_mapAB {
	a_id int not null,
	b_id int not null
}
```

2）方式灵活，可以表示1:N,N:1,N:M关系，缺点需要进行连表查询。


**映射表：显示映射表，隐式映射表**
如：restbus中的schedule就是隐式映射表，关联路线与车辆，之所以说是隐式，
主要是他现实中有对应的实体，即时刻表，很容易认为是一个独立实体。
而以上的tb_mapAB就是显示的，一，映射关系容易理解，二，表名也不好取，干脆
取名表A表B的映射。


**从三方面考察表字段的设计，查询***，修改**，删除***
schedule里面要不要把司机编号添加进去，不应该添加，因为如果车辆与司机的对应关系发生变化，schedule这边也需要修改，完全可以通过车辆编号动态找出对应司机编号。从冗余性角度讲，schedule里面添加司机编号也是冗余的。而适当的冗余能够增加查询速度，目前这边表规模不大对效率影响不大，而且冗余性数据一般不会发生变化的吧。