当其他表中的值为null时,选择表行

时间:2016-07-04 02:13:39

标签: sql sql-server

有没有办法使用另一个表中的值来选择行?

enter image description here

我想使用table2

选择表1中的数据

enter image description here

输出

enter image description here

enter image description here

我在table1中选择值时有2个实例,这就是我试图在这个上使用case的原因,我不确定它是否正确。

select
case when table2.s_num is Null and table2.s_div is Null then
(select * from table1 where table1.item_num = table2.i_num)
from table1, table2

以下是我的实例:

1. if t2.s_num is null and t2.s_div is null then select * from t1 where     t1.item_num = t2.i_num 
2. if t2.s_num is null and t2.s_div is not null then select * from t1 where t1.item_num = t2.i_num and t1.store_div = t2.s_div

我在sql中不是很好,有什么想法吗?谢谢!

6 个答案:

答案 0 :(得分:1)

  

有没有办法使用另一个表中的值来选择行?

您应该使用join

首先,查看此查询的输出:

select *
from table1 t1
join table2 t2 on t2.i_num = t1.item_num

了解加入的工作原理?它将i_numitem_num匹配,并仅返回匹配的行(即inner join,默认类型)。

你的两个"实例"实际上有一个更复杂的连接条件,这样的东西应该表达它:

select *
from table1 t1
join table2 t2 on t2.i_num = t1.item_num and (t2.s_div is null or t2.s_div = t1.store_div)

您还希望过滤到s_num为空的行,因此只需添加where

select *
from table1 t1
join table2 t2 on t2.i_num = t1.item_num and (t2.s_div is null or t2.s_div = t1.store_div)
where t2.s_num is null

答案 1 :(得分:0)

加入即可

select t1.* 
from
table1 t1
join table2 t2
on t1.item_num = t2.i_num
where t2.s_num is null and t2.s_div is null

答案 2 :(得分:0)

使用table2 LEFT JOIN到table1

SELECT store_num = coalesce(t2.s_num, t1.store_num),
       item_num  = t2.i_num,
       store_div = colaesce(t2.s_div, t1.store_div),
       t1.price
FROM   table2 t2
       LEFT JOIN table1 t1 ON t2.i_num = t1.item_num

答案 3 :(得分:0)

你可以试试这个。如果ORAND都为空,则WHERE clause中的s_num更改为s_div

SELECT *
FROM TABLE1 T1
INNER JOIN TABLE1 T2
ON T2.I_NUM = T1.ITEM_NUM
WHERE T2.S_NUM IS NULL OR T2.S_DIV IS NULL

答案 4 :(得分:0)

SELECT A.*  
FROM table1 AS A JOIN table2 AS B ON (B.i_num = A.item_num)
    WHERE A.item_num IN (SELECT i_num FROM table1 WHERE s_num=null AND s_div=null);  

答案 5 :(得分:0)

您可以使用LEFT JOIN

select
from table1
left join table2
on table2.s_num is null
and (table2.s_div = table1.store_div or table2.s_div is null)
and table1.item_num = table2.i_num

如您所说,如果table2.s_num不为空,则您不会加入table2,如果table2.s_num is null匹配,则会table2.s_div = table1.store_div or table1.store_div is null,如果匹配,则为table1.item_num = table2.i_num意味着{{1}}将被计算。