# Muchos a Muchos

## Diseño conceptual

![](https://2075084147-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZGNM3do-IXXEttoVGo%2F-M_0_BX-c2v8yC4A5Nzm%2F-M_0wxsuJh1jwm6Y2uL4%2Fimage.png?alt=media\&token=9f30070b-ac44-4cad-ad86-a69741782a19)

En el diseño conceptual se puede expresar con en la imagen anterior pero cuando se va a programar se genera una tablan intermedia o también se coloca en el diseño físico.

## &#x20;Diseño Físico

### Llaves naturales

![](https://2075084147-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZGNM3do-IXXEttoVGo%2F-M_0_BX-c2v8yC4A5Nzm%2F-M_11YUITOV29bwiXP9e%2Fimage.png?alt=media\&token=b1bd8f09-f788-435e-a668-bf2fc00e672d)

```sql
CREATE TABLE factura (
  numero_factura int4 NOT NULL, 
  anio           int4 NOT NULL, 
  forma_pago     varchar(100) NOT NULL, 
  total          float8 NOT NULL, 
  PRIMARY KEY (numero_factura, 
  anio));
  
  CREATE TABLE producto (
  codigo_barras   varchar(255) NOT NULL, 
  nombre_producto varchar(255) NOT NULL, 
  precio          float8 NOT NULL, 
  cantidad        int4 NOT NULL, 
  PRIMARY KEY (codigo_barras));

CREATE TABLE detalle_factura (
  numero_factura int4 NOT NULL, 
  anio_factura   int4 NOT NULL, 
  codigo_barras  varchar(255) NOT NULL, 
  precio         float8 NOT NULL, 
  cantidad       int4 NOT NULL, 
  PRIMARY KEY (numero_factura, 
  anio_factura, 
  codigo_barras));
ALTER TABLE detalle_factura ADD CONSTRAINT fk_factura FOREIGN KEY (numero_factura, anio_factura) REFERENCES factura (numero_factura, anio);
ALTER TABLE detalle_factura ADD CONSTRAINT fk_producto FOREIGN KEY (codigo_barras) REFERENCES producto (codigo_barras);

```

### Llaves sustitutas&#x20;

![](https://2075084147-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MZGNM3do-IXXEttoVGo%2F-M_11_a88TMIryErP-tN%2F-M_1HJgWthAkYUgyETAu%2Fimage.png?alt=media\&token=46e3617a-4bc1-4cf1-8d0d-db673c8e135c)

```sql
CREATE TABLE factura (
  id             SERIAL NOT NULL, 
  numero_factura int4 NOT NULL, 
  anio           int4 NOT NULL, 
  forma_pago     varchar(100) NOT NULL, 
  total          float8 NOT NULL, 
  PRIMARY KEY (id), 
  CONSTRAINT uc_factura 
    UNIQUE (numero_factura, anio));
    
    
CREATE TABLE producto (
  id              SERIAL NOT NULL, 
  codigo_barras   varchar(255) NOT NULL, 
  nombre_producto varchar(255) NOT NULL, 
  precio          float8 NOT NULL, 
  cantidad        int4 NOT NULL, 
  PRIMARY KEY (id), 
  CONSTRAINT uc_producto 
    UNIQUE (codigo_barras));
    
CREATE TABLE detalle_factura (
  id          SERIAL NOT NULL, 
  id_factura  int4 NOT NULL, 
  id_producto int4 NOT NULL, 
  cantidad    int4 NOT NULL, 
  precio      float8 NOT NULL, 
  PRIMARY KEY (id), 
  CONSTRAINT uc_detalle_factura 
    UNIQUE (id_factura, id_producto));
```
