左外连接查询根据其条件无法正常工作

时间:2017-02-02 09:56:12

标签: sql-server

我通过sql select查询过滤多个表的数据,为此我在c#.net中使用了左外连接。因此,通过排除此查询过滤器无法正常工作。

例如:我的数据的branchid为1,yearid为1.因此,当执行查询时,它工作正常,即它显示只有其分支和年份id为1的数据。

其branchid为2和yearid的其他数据为1.因此,当我根据此过滤器排除查询时,它显示branchid为1,yearid为1,branchid为2,yearid为1。

表示第二次显示branch和yearid的完整数据。所以当时过滤器不起作用。

这是我的查询

SELECT DISTINCT
        Client.clientname AS ClientName ,
        RetailInvoice.invoiceno AS InvoiceNo ,
        RetailInvoice.pono AS PoNO ,
        RetailInvoice.issuedate AS IssueDate ,
        RetailInvoice.duedate AS DueDate ,
        RetailInvoice.discount AS Discount ,
        RetailInvoice.shipping AS Shipping ,
        RetailInvoice.tax AS Tax ,
        RetailInvoice.vat AS Vat ,
        RetailInvoice.sese AS Sese ,
        RetailInvoice.paymenttype AS PaymentType ,
        RetailInvoice.chequeno AS Chequeno ,
        RetailInvoice.totalamt AS TotalAmt ,
        RetailInvoice.description AS Description ,
        RetailInvoice.paymentpaid AS PaymentPaid ,
        RetailInvoice.subtotal AS Subtotal ,
        RetailInvoicePayment.productid AS ProductName ,
        RetailInvoicePayment.uom AS Uom ,
        RetailInvoicePayment.quantity AS Quantity ,
        RetailInvoicePayment.price AS Price
FROM    tbl_retailinvoice RetailInvoice
        LEFT OUTER JOIN tbl_retailinvoicepayment RetailInvoicePayment 
             ON RetailInvoice.invoiceno = RetailInvoicePayment.invoiceno
        LEFT OUTER JOIN tbl_clientdetail Client 
             ON RetailInvoice.clientid = Client.clientid
WHERE   RetailInvoice.BranchID = 1
        AND RetailInvoice.YearID = 1
        AND RetailInvoice.invoiceno = 1;

1 个答案:

答案 0 :(得分:0)

在您的查询中:

FROM    tbl_retailinvoice RetailInvoice
        LEFT OUTER JOIN tbl_retailinvoicepayment RetailInvoicePayment 
             ON RetailInvoice.invoiceno = RetailInvoicePayment.invoiceno
        LEFT OUTER JOIN tbl_clientdetail Client 
             ON RetailInvoice.clientid = Client.clientid
WHERE   RetailInvoice.BranchID = 1
        AND RetailInvoice.YearID = 1
        AND RetailInvoice.invoiceno = 1;

WHERE子句中的所有三个条件都集中在表RetailInvoice上。你说即使你改变where条件:

WHERE   RetailInvoice.BranchID = 2
        AND RetailInvoice.YearID = 1
        AND RetailInvoice.invoiceno = 1;

..它仍然显示RetailInvoice.BranchID = 1的行。模糊地说,这不应该是可能的,因为你的WHERE子句将明确规定只有BranchID为2的行才是回。我说"含糊地说"因为我在这里没有很多信息,但原则上你所说的似乎是荒谬的。

问题描述中的某些内容并不构成我的意思。此问题不应与LEFT JOIN相关,因为WHERE条件都没有指向LEFT JOIN包含的其中一个表。换句话说,问题似乎在其他地方。

  

仅供参考,LEFT JOIN仅表示"显示来自的信息   RetalInvoice即使没有匹配的行   RetailInvoicePayment或客户表。"   而不是INNER JOIN,它只显示所有三个表中都存在匹配行的数据。