【发布时间】:2016-05-27 20:37:11
【问题描述】:
我已经为此工作了几天,还没有找到修复或解决方案。即使一个表(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
【问题讨论】:
-
不用过多讨论,也许您可以在您的条件
AND (table2.cus_no = table3.cd_tp_1_cust_no OR table3.cd_tp_1_cust_no IS NULL)中允许 table3 值为空? -
不行,我也试过了,table2.cus_no = table3.cd_tp_1_cust_no OR table3.cd_tp_1_cust_no IS NULL AND table2.cus_no IS NULL。
标签: php sql-server-2008