gpt4 book ai didi

mysql - 从表中选择总和,其中字段位于另一个带有字段的表中

转载 作者:行者123 更新时间:2023-11-29 13:23:43 25 4
gpt4 key购买 nike

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

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

哪里$idid来自 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`)
);

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

如有任何帮助,我们将不胜感激。

最佳答案

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

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

关于mysql - 从表中选择总和,其中字段位于另一个带有字段的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20426932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com