简体   繁体   中英

How to use SUM when foreign key and primary key matched in MYSQL

Currently I have 2 tables which is document and item table.

CREATE TABLE IF NOT EXISTS `document` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dateDoc` datetime NOT NULL,
  `numDoc` varchar(45) NOT NULL,
  `idCategory` int(11) DEFAULT NULL,
  `subject` varchar(200) DEFAULT NULL,
  `status` varchar(1) NOT NULL DEFAULT 'A',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=155 ;

CREATE TABLE IF NOT EXISTS `item` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `idDoc` int(11) NOT NULL,
  `numItem` int(11) NOT NULL,
  `amount` decimal(14,4) NOT NULL,
  `idTax` varchar(30) DEFAULT NULL,
  `rateTax` decimal(5,2) DEFAULT NULL,
  `amtTax` decimal(12,4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=244 ;

How to sum up the amount and amtTax in Table 'item' if document(id) = item (idDoc).

For example :

(document table)

Document id = 1;

(item table)

id = 1;
idDoc = 1;
amount = 50.00;
amtTax = 10.00;


id = 2;
idDoc = 1;
amount = 30.00;
amtTax = 6.60;

I suppose to get RM96.60.

How to sum up the amount and amtTax in mysql as a new column named (Total) if idDoc match with document table's id? Thank you for your help!

If you want to select all documents with their sums of amounts and amt taxes, use a join with group by over the documents:

SELECT SUM(item.amount) + SUM(item.amtTax) AS Total
FROM document
LEFT JOIN item
    ON document.id = item.idDoc

If you want to select just a single document (eg the one with id 1), you don't need to use group by, just add where clause:

SELECT document.*, sum(item.amount) + sum(item.amtTax) as Total
FROM document LEFT JOIN item ON document.id = item.idDoc
WHERE document.id = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM