gpt4 book ai didi

带有条件的多个表的 mySQL Left Join

转载 作者:行者123 更新时间:2023-11-29 01:33:21 24 4
gpt4 key购买 nike

我有一个问题。我有 4 张 table :

Invoice_Payment、发票、客户和日历

基本上,我有以下查询,效果很好,除了没有 date_due 的月份不会返回。即仅返回包含 date_due 的月份。

注意:日历表仅列出一年中的每一天。它包含一个 col 调用 date_field

数据库:http://oberto.co.nz/jInvoice.txt

预期输出:我当前的查询(如下)将返回类似以下内容的内容:

month       total
August 5
September 0
October 196
November 205
December 214
January 229

注意到九月没有返回吗?这是因为表Invoice_Payment没有date_due记录

我想我必须使用左连接并使用以下内容连接日历表:LEFT JOIN 日历 ON Invoice_Payments.date_paid = Calendar.date_field。但我运气不好

SELECT MONTHNAME(Invoice_Payments.date_paid) as month, SUM(Invoice_Payments.paid_amount) AS total
FROM Invoice, Client, Invoice_Payments
WHERE Client.registered_id = 1
AND Client.id = Invoice.client_id
And Invoice.id = Invoice_Payments.invoice_id
AND date_paid IS NOT NULL
GROUP BY YEAR(Invoice_Payments.date_paid), MONTH(Invoice_Payments.date_paid)

感谢任何帮助。

最佳答案

听起来您正在尝试查找某个范围内所有日期的值,无论是否有值。假设我们有一个日历表,其结构如下:

Create Table Calendar
(
[Date] not null Primary Key
)

您的查询可能如下所示(其中 X 和 Y 代表您正在调查的范围的开始日期和结束日期):

Select Year(C.Date), MonthName(C.Date) As Month
, Coalesce(Sum(IP.paid_amount),0) As Total
From Calendar As C
Left Join (Invoice As I
Join Client As C1
On C1.id = I.client_id
And C.registered_id = 1
Join Invoice_Payments As IP
On IP.Invoice_id = I.Id)
On IP.date_paid = C.date
Where C.Date Between X and Y
Group By Year(C.Date), MonthName(C.Date)

从技术上讲,上面的查询应该可以解决问题。但是,另一种选择是使用您在评论中查询的派生表:

Select Year(C.Date), MonthName(C.Date) As Month
, Coalesce(Sum(Z.paid_amount),0) As Total
From Calendar As C
Left Join (
Select IP.date_paid, IP.paid_amount
From Invoice As I
Join Client As C1
On C1.id = I.client_id
And C.registered_id = 1
Join Invoice_Payments As IP
On IP.Invoice_id = I.Id
) As Z
On Z.date_paid = C.date
Where C.Date Between X and Y
Group By Year(C.Date), MonthName(C.Date)

关于带有条件的多个表的 mySQL Left Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704095/

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