从表中选择sum,其中field在另一个带有field的表中

时间:2013-12-06 14:55:47

标签: mysql join sum

也许标题有点令人困惑,所以这是我想要开始工作的查询:

select sum(amount+discount) from `payments` where `id_invoice` in (select `id` from `invoices` where `id_client`='$id'

其中$id是来自id

的客户的clients

这是3个表结构:

CREATE TABLE IF NOT EXISTS `clients` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `address` text NOT NULL,
  `phone` varchar(255) NOT NULL,
  `fax` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `company` varchar(255) NOT NULL,
  `mobile` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `invoices` (
  `id` int(11) NOT NULL,
  `id_client` int(11) NOT NULL,
  `invoice_number` int(11) NOT NULL,
  `date_created` int(11) NOT NULL,
  `po_number` varchar(255) NOT NULL,
  `terms` text NOT NULL,
  `notes` text NOT NULL,
  `status` varchar(255) NOT NULL DEFAULT 'Draft',
  `date_saved` int(11) NOT NULL,
  `total` varchar(255) NOT NULL,
  `issue_date` int(11) NOT NULL,
  `due_date` int(11) NOT NULL,
  `cancelled` varchar(255) NOT NULL DEFAULT 'no',
  `tax_percentage` varchar(255) NOT NULL DEFAULT '20',
  PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `payments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_invoice` int(11) NOT NULL,
  `the_date` int(11) NOT NULL,
  `method` varchar(255) NOT NULL,
  `amount` varchar(255) NOT NULL,
  `receipt_no` int(11) NOT NULL,
  `discount` varchar(255) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);

所以我想得到每个客户的总付款额+折扣......

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

在我看来,最好将表格连在一起,然后在对客户名称进行分组时执行总结:

SELECT c.name, SUM(p.amount + p.discount) AS MyCalc
FROM invoices AS i
  JOIN payments AS p ON p.id_invoice = i.id'
  JOIN clients AS c ON c.id = i.id_client
GROUP BY c.name

然后,您可以添加WHERE子句以进一步限制结果:

SELECT c.name, SUM(p.amount + p.discount) AS MyCalc
FROM invoices AS i
  JOIN payments AS p ON p.id_invoice = i.id'
  JOIN clients AS c ON c.id = i.id_client
WHERE id_client = $id
GROUP BY c.name