左外连接不起作用?

我有一个查询,使用两个连接的LEFT OUTER JOIN从三个表中提取数据。我需要查询以返回最左边的(Salesrep表)信息,即使在两个右边的表(分别是处方药和处方)中没有对应的数据也是如此。当我在WHERE子句中没有日期参数的情况下运行此查询时,我得到了预期的回报,但是当我包含日期参数时,在没有任何销售代表匹配数据的情况下,我什么也没有得到返回。我至少需要查看查询中请求的salesrep表列。


这是查询...非常感谢您的帮助。


SELECT  salesrep.salesrepid as SalesRepID,

        salesrep.fname as SalesrepFName,

        salesrep.lname as SalesRepLName,

        salesrep.fname+' '+salesrep.lname as SalesRepFullName,

        prescriber.dea_no as PDeaNo,

        prescriber.lname+', '+prescriber.fname as DocName,

        CONVERT(VARCHAR(8), prescriptions.filldate, 1) as FillDate,

        prescriptions.drugname as DrugName,

        prescriptions.daysupply as Supply,

        prescriptions.qtydisp as QtyDisp,

        prescriptions.rx_no as Refill,

        prescriptions.copay as Sample,

        ROUND(prescriptions.AgreedToPay-(prescriptions.AgreedToPay*.07),2) as AgreedToPay,

        prescriptions.carrierid as CarrierID

FROM    salesrep

  LEFT OUTER JOIN prescriber on salesrep.salesrepid = prescriber.salesrepid

  LEFT OUTER JOIN prescriptions on prescriber.dea_no = prescriptions.dea_no

  WHERE salesrep.salesrepid = 143 AND

        prescriptions.filldate >= '09-01-12' AND

        prescriptions.filldate <= '09-17-12'

ORDER BY prescriptions.filldate


紫衣仙女
浏览 553回答 3
3回答

白衣染霜花

您应该将约束prescriptions.filldate移到连接ON条件中,并将其从where子句中删除:LEFT OUTER JOIN prescriptions ON prescriber.dea_no = prescriptions.dea_no&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;AND prescriptions.filldate >= '09-01-12'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;AND prescriptions.filldate <= '09-17-12'否则,没有条目的prescriptions结尾以nulls 开头prescriptions.filldate,该WHERE子句将其丢弃。

临摹微笑

这是因为您的prescriptions.filldate不等式正在过滤掉salesrep列中没有值的prescriptions.filldate行。因此,如果存在空值(右表中没有匹配数据),则日期筛选器将滤除包括salesrep数据在内的整个行-因为它们null不在两个日期之间。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server