当一个表没有记录

时间:2016-05-27 20:37:11

标签: php sql-server-2008

我已经做了好几天了,还没有找到解决办法或解决方案。即使一个表(table3)没有匹配的数据,我也试图返回所有结果。我需要返回的默认值是table1.ord_no,table2.item_no,table1.cus_no,table2.unit_price,table2.item_desc_1。如果table3中没有匹配将给出我.prc_or_disc_1字段的匹配,我只需要回显0.但是当我的查询现在坐在它时,每当table3为空时它都不返回我因为我的AND table2而假设。 cus_no = table3.cd_tp_1_cust_no语句。但是从table1和table2获得结果会很棒。我试图使用左连接,左外连接和外连接。有什么问题吗?

 SELECT table1.ord_no, table2.item_no, table2.item_desc_1,
      table1.cus_no, table2.unit_price, table3.prc_or_disc_1, table2.line_seq_no
    FROM table2 JOIN table1
        ON table1.ord_no = table2.ord_no
      LEFT OUTER JOIN table3 on table2.item_no = table3.cd_tp_1_item_no
    Where table2.ord_no = $multi_orders
      AND table2.cus_no = table3.cd_tp_1_cust_no
     AND getdate() BETWEEN start_dt AND end_dt
    ORDER BY table2.line_seq_no

我也尝试了这个荒谬的查询,这个查询几乎有用,但是给了我一个错误,说我不能收到多个结果。

IF (SELECT table3.prc_or_disc_1
FROM table3 join table1 on table1.cus_no = table3.cd_tp_1_cust_no
JOIN table2
ON table1.ord_no = table2.ord_no WHERE table1.ord_no = $multi_orders
AND table3.cd_tp_1_item_no = table2.item_no
AND table3.cd_tp_1_cust_no = table1.cus_no
AND getdate() between start_dt and end_dt) > 0
BEGIN
(SELECT table1.ord_no
, table2.item_no
, table2.item_desc_1
,table1.cus_no
, table2.unit_price
, table3.prc_or_disc_1
FROM table1
JOIN table2
ON table1.ord_no = table2.ord_no
JOIN cicmpy ON table1.cus_no = cicmpy.debcode
LEFT JOIN table3 on table1.cus_no = table3.cd_tp_1_cust_no
WHERE table1.ord_no = $multi_orders
AND table3.cd_tp_1_item_no = table2.item_no
AND table3.cd_tp_1_cust_no = table1.cus_no
AND getdate() between start_dt and end_dt)
END
ELSE
BEGIN
SELECT table1.ord_no
, table2.item_no
, table2.item_desc_1
,table1.cus_no
, table2.unit_price
FROM table1
JOIN table2
ON table1.ord_no = table2.ord_no
JOIN cicmpy ON table1.cus_no = cicmpy.debcode
WHERE table1.ord_no = $multi_orders;
END

1 个答案:

答案 0 :(得分:0)

您应该将条件saveRow置于table2.cus_no = table3.cd_tp_1_cust_no条件而不是LEFT OUTER JOIN条件。 当WHERE中没有匹配的行时,不仅会给你一个结果,而且对我来说这似乎也更符合逻辑,要做更多的窄连接而不是稍后过滤。

因此您的查询将成为:

table3
相关问题