Ver originalCREATE TABLE IF NOT EXISTS `contratos` ( `idcontrato` varchar(20) NOT NULL, `valorcontrato` mediumint(40) NOT NULL, PRIMARY KEY (`idcontrato`)) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `contratos` (`idcontrato`, `valorcontrato`) VALUES('C1', 25000); CREATE TABLE IF NOT EXISTS `facturas` ( `nfactura` varchar(30) NOT NULL, `valorfactura` int(50) NOT NULL, PRIMARY KEY (`nfactura`)) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `facturas` (`nfactura`, `valorfactura`) VALUES('F1', 1000),('F2', 5000); CREATE TABLE IF NOT EXISTS `totalcontratos` ( `idcontrato` varchar(20) NOT NULL, `nfactura` varchar(30) NOT NULL, PRIMARY KEY (`idcontrato`,`nfactura`), KEY `nfactura` (`nfactura`)) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `totalcontratos` (`idcontrato`, `nfactura`) VALUES('C1', 'F1'),('C1', 'F2'); ALTER TABLE `totalcontratos` ADD CONSTRAINT `totalcontratos_ibfk_2` FOREIGN KEY (`idcontrato`) REFERENCES `contratos` (`idcontrato`), ADD CONSTRAINT `totalcontratos_ibfk_1` FOREIGN KEY (`nfactura`) REFERENCES `facturas` (`nfactura`);
Ver originalSELECT (valorcontrato - SUM( valorfactura ) )restoFROM contratos cINNER JOIN totalcontratos tc ON c.idcontrato = tc.idcontratoINNER JOIN facturas f ON tc.nfactura = f.nfacturaGROUP BY c.idcontrato