如果没有使用连接

时间:2017-10-28 07:27:20

标签: sql sql-server sql-server-2008

如果没有使用连接返回记录,则在SQL查询下面返回NULL值。

我的查询:

SELECT 
    ISNULL((SELECT SR_No
            FROM Product
            WHERE SR_No in ('8877','9911')), NULL)

基本上我需要检查SR_No表中Product是否可用。

如何修改我的脚本以获得如下输出:

表格 - > Item_M:

+-------+---------+
| SR_No | Asso_Id |
+-------+---------+
|  4455 |     100 |
|  4455 |     200 |
|  4455 |     300 |
|  8877 |     500 |
|  9911 |     600 |
+-------+---------+

表格 - >产品:

| SR_No | Pro_N | Pro_Sc |
+-------+-------+--------+
|  4455 | SA    | S      |
|  8877 | BT    | B      |
|       |
+-------+-------+--------+

预期产出:

+-------+-------+--------+
| SR_No | Pro_N | Pro_Sc |
+-------+-------+--------+
| 8877  | BT    | B      |
| NULL  | NULL  | NULL   |
+-------+-------+--------+

2 个答案:

答案 0 :(得分:2)

这看起来非常适合使用Table Valued Constructor来创建您要查找的项目的表格,然后您可以LEFT JOIN产品(和可能的项目)表格,命令选择性地显示其他列,如果符合条件,则为NULL:

-- If you want the SR_No number listed along with NULLs
SELECT x.SR_No, p.Pro_N, p.Pro_Sc
FROM (values (8877),(1234)) as x(SR_No)
LEFT OUTER JOIN Product p
on x.SR_No = p.SR_No;

输出:

SR_No   Pro_N   Pro_Sc
8877    BT      B
1234    (null)  (null)

如果你不想在空值旁边显示SR_No值:

-- If you want the SR_No listed as NULL instead
SELECT p.SR_No, p.Pro_N, p.Pro_Sc
FROM (values (8877),(1234)) as x(SR_No)
LEFT OUTER JOIN Product p
on x.SR_No = p.SR_No;

,并提供:

SR_No   Pro_N   Pro_Sc
8877    BT      B
(null)  (null)  (null)

第二种方法的问题是,如果存在多个不匹配项,您将显示多行NULL列,这对于使用此查询的代码不太可能有用。

如果您需要进一步限定产品必须存在项目行,请调整查询:

LEFT OUTER JOIN Product p
on x.SR_No = p.SR_No AND EXISTS (SELECT 1 FROM Item_M i WHERE i.SR_No = p.SR_No);

SqlFiddle here

答案 1 :(得分:0)

试试这个:

SELECT CASE WHEN SR_No IN ('8877','9911') THEN SR_No END AS SR_No,
       CASE WHEN SR_No IN ('8877','9911') THEN Pro_N END AS Pro_N,
       CASE WHEN SR_No IN ('8877','9911') THEN Pro_Sc END AS Pro_Sc
FROM Product

SQL Fiddle

您可以修改它进入子查询而不是('8877','9911')