0
I have the following Mysql tables:
CREATE TABLE IF NOT EXISTS `tcc2`.`catalogo` (
`idPHL` BIGINT(20) UNSIGNED NOT NULL,
`isbn` VARCHAR(15) NULL DEFAULT NULL,
`titulo` LONGTEXT ,
`autor` LONGTEXT NULL DEFAULT NULL,
`edicao` VARCHAR(45) NULL DEFAULT NULL,
`anoPublicacao` LONGTEXT NULL DEFAULT NULL,
`editora` LONGTEXT NULL DEFAULT NULL,
`qtdEx` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`idPHL`));
CREATE TABLE IF NOT EXISTS `tcc2`.`disciplina_livros` (
`livro` BIGINT(20) UNSIGNED NOT NULL,
`disciplina` VARCHAR(10) NOT NULL,
`tipoReferencia` INT(11) NOT NULL,
PRIMARY KEY (`livro`, `disciplina`),
INDEX `fk_catalogo_has_disciplina_disciplina1_idx` (`disciplina` ASC),
INDEX `fk_catalogo_has_disciplina_catalogo1_idx` (`livro` ASC),
INDEX `fk_disc_livro_tipo_idx` (`tipoReferencia` ASC),
CONSTRAINT `fk_disc_disciplina`
FOREIGN KEY (`disciplina`)
REFERENCES `tcc2`.`disciplina` (`codDisciplina`)
ON UPDATE CASCADE,
CONSTRAINT `fk_disc_livro_tipo`
FOREIGN KEY (`tipoReferencia`)
REFERENCES `tcc2`.`tipoReferencia` (`idTipoRef`)
ON UPDATE CASCADE,
CONSTRAINT `fk_disciplina_catalogo`
FOREIGN KEY (`livro`)
REFERENCES `tcc2`.`catalogo` (`idPHL`));
CREATE TABLE IF NOT EXISTS `tcc2`.`tipoReferencia` (
`idTipoRef` INT(11) NOT NULL AUTO_INCREMENT,
`descricao` VARCHAR(25) NOT NULL,
PRIMARY KEY (`idTipoRef`));
CREATE TABLE IF NOT EXISTS `tcc2`.`disciplina` (
`codDisciplina` VARCHAR(10) NOT NULL,
`nome` VARCHAR(45) NOT NULL,
PRIMARY KEY (`codDisciplina`));
I need to make a query where the name of the discipline is returned, the title, the number of copies and the sum of the number of copies. I’m trying the following:
select d.nome, ca.titulo, ca.qtdEx, sum(ca.qtdEx) from catalogo as ca, disciplina_livros as dl,
disciplina as d
where dl.disciplina = 'EDU140' and ca.idPHL = dl.livro and
dl.tipoReferencia = 1
group by ca.titulo;
The result is as below, the column sum(ca.qtdEx)
should return 18 and not 324.
Modeling:
How do I return the sum of the qtdEx column?
Use joins to join the tables of your query and insert ALL fields that are not part of the sum within the group by. You will probably get the expected result or a series of duplicated lines that are soiling this result.
– gmsantos
I didn’t get the Join part.
– Costa.Gustavo
https://stackoverflow.com/questions/5294311/difference-between-these-two-joining-table-approaches
– gmsantos
https://www.w3schools.com/sql/sql_join_inner.asp
– Rogério Dec
You can create a view to simplify the query and in the view query do the sum, see here an example
– WMomesso