上面的截图是我的表结构..
发票表
CREATE TABLE BASE_TInvoice
(
InvoicePaymentId BIGINT IDENTITY(1,1) NOT NULL,
PaymentDate DATE NOT NULL,
InvoicePaymentMethod VARCHAR(45) NOT NULL,
IsCashPayment BIT NOT NULL,
Note VARCHAR(5000) NULL,
IsRecordStatus BIT DEFAULT 1 NOT NULL
PRIMARY KEY(InvoicePaymentId)
)
现金发票表
CREATE TABLE BASE_TCashInvoice
(
CashInvoicePaymentId BIGINT IDENTITY(1,1) NOT NULL,
InvoicePaymentId BIGINT NOT NULL,
CashAmount MONEY NULL,
CashReceived MONEY NULL,
CashBalance MONEY NULL,
IsRecordStatus BIT DEFAULT 1 NOT NULL
PRIMARY KEY(CashInvoicePaymentId)
)
我使用 Right Join 来检索数据。
SELECT BASE_TInvoice.InvoicePaymentId, BASE_TInvoice.PaymentDate, BASE_TInvoice.InvoicePaymentMethod, BASE_TInvoice.IsCashPayment, BASE_TCashInvoice.CashAmount, BASE_TCashInvoice.CashReceived, BASE_TCashInvoice.CashBalance
FROM BASE_TCashInvoice RIGHT OUTER JOIN BASE_TInvoice ON BASE_TCashInvoice.InvoicePaymentId = BASE_TInvoice.InvoicePaymentId
WHERE (BASE_TInvoice.IsRecordStatus = 1) AND (BASE_TCashInvoice.IsRecordStatus IS NULL OR BASE_TCashInvoice.IsRecordStatus = 1) AND (BASE_TInvoice.InvoicePaymentId = 1)
一旦我将 BASE_TCashInvoice Status (IsRecordStatus) 设置为 false 并检索数据,我就会变得空白,下面是两个屏幕截图。
我认为问题出在 where 子句中(BASE_TCashInvoice.IsRecordStatus IS NULL OR BASE_TCashInvoice.IsRecordStatus = 1)
如何在 BASE_TCashInvoice 记录 InvoicePaymentId 1 和 IsRecordStatus 变为 false 时检索准确数据只需要显示 BASE_TInvoice 表记录。答案应该像下面的截图
是的,问题似乎是涉及
CashInvoice
表的条件。它应该从 移动WHERE
到ON
。除此之外,我还要对查询进行一些更改,以使其更具可读性:LEFT JOIN
而不是RIGHT JOIN
。这是一种风格问题,但RIGHT
许多人对连接感到困惑。更糟糕的是,如果查询合并LEFT
并RIGHT
连接。我建议您在任何地方都使用一个或另一个,优先使用LEFT
. 这样,“基本”表可以始终放在第一位,然后是FROM
最后的“可选”表。使未来的读者更容易识别哪个是哪个,尤其是当查询有很多连接时。;
在每个语句的末尾添加一个语句终止符 ( )。微软建议,在未来的版本中,非终止查询将抛出错误(有些已经这样做了)。WHERE
移动ON
,查询变为: