Ver Mensaje Individual
  #10 (permalink)  
Antiguo 04/02/2013, 16:01
jurena
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Cáceres
Mensajes: 3.735
Antigüedad: 17 años
Puntos: 300
Respuesta: update con un insert

Echa un vistazo a lo que yo te propongo. Mira el ejemplo.
Código MySQL:
Ver original
  1. CREATE TABLE IF NOT EXISTS `contratos` (
  2.   `idcontrato` varchar(20) NOT NULL,
  3.   `valorcontrato` mediumint(40) NOT NULL,
  4.   PRIMARY KEY (`idcontrato`)
  5.  
  6. INSERT INTO `contratos` (`idcontrato`, `valorcontrato`) VALUES
  7. ('C1', 25000);
  8.  
  9.  
  10. CREATE TABLE IF NOT EXISTS `facturas` (
  11.   `nfactura` varchar(30) NOT NULL,
  12.   `valorfactura` int(50) NOT NULL,
  13.   PRIMARY KEY (`nfactura`)
  14.  
  15. INSERT INTO `facturas` (`nfactura`, `valorfactura`) VALUES
  16. ('F1', 1000),
  17. ('F2', 5000);
  18.  
  19. CREATE TABLE IF NOT EXISTS `totalcontratos` (
  20.   `idcontrato` varchar(20) NOT NULL,
  21.   `nfactura` varchar(30) NOT NULL,
  22.   PRIMARY KEY (`idcontrato`,`nfactura`),
  23.   KEY `nfactura` (`nfactura`)
  24.  
  25. INSERT INTO `totalcontratos` (`idcontrato`, `nfactura`) VALUES
  26. ('C1', 'F1'),
  27. ('C1', 'F2');
  28.  
  29. ALTER TABLE `totalcontratos`
  30.   ADD CONSTRAINT `totalcontratos_ibfk_2` FOREIGN KEY (`idcontrato`) REFERENCES `contratos` (`idcontrato`),
  31.   ADD CONSTRAINT `totalcontratos_ibfk_1` FOREIGN KEY (`nfactura`) REFERENCES `facturas` (`nfactura`);

Y luego lanza esta consulta
Código MySQL:
Ver original
  1. valorcontrato - SUM( valorfactura )
  2. )resto
  3. FROM contratos c
  4. INNER JOIN totalcontratos tc ON c.idcontrato = tc.idcontrato
  5. INNER JOIN facturas f ON tc.nfactura = f.nfactura
  6. GROUP BY c.idcontrato