Lunes, 21 Mayo 2012
Del enunciado revisado en la presentación de DDL, que dice:

Crear las siguientes tablas (de manera relacional) en la base de datos ejemplo1:

  • PRODUCTO, los campos son product_id, nombre,sku, imagen, precio, cantidad, fecha.
  • CATEGORIAS, los campos son category_id, nombre categoria.
  • CATEGORIA_PRODUCTO, los campos son product_id, category_id.

SOLUCIÓN

En la tabla categoria_producto ambos campos deben ser primarios y foraneos para cumplir el concepto de integridad referencial.

El SQL propuesto es el siguiente:

CREATE TABLE productos(
  product_id  serial  NOT NULL,
  nombre    character varying(200) NOT NULL,
  sku    character varying(50) NOT NULL,
  imagen    character varying(50) NULL,
  precio     numeric NOT NULL,
  cantidad  integer  NOT NULL,
  fecha    date NOT NULL,

  CONSTRAINT pk_producto PRIMARY KEY (product_id)
);

CREATE TABLE categorias(
  category_id  serial NOT NULL,
  nombre_cat  character varying(200),

  CONSTRAINT pk_categorias PRIMARY KEY(category_id)  
);

CREATE TABLE categoria_producto(
  category_id  serial NOT NULL,
  product_id  serial NOT NULL,

  -- defino llaves primarias  
  CONSTRAINT pk_cat_prod  PRIMARY KEY(category_id,product_id),
  --defino llaves secundarias
  CONSTRAINT fk_productos FOREIGN KEY (product_id) 
  REFERENCES productos (product_id)  ,

  CONSTRAINT fk_categorias FOREIGN KEY (category_id) 
  REFERENCES categorias (category_id)
);

¿Dudas, comentar el post?


blog comments powered by Disqus