2017-08-10 48 views
1

我不知道该怎么解释我所需要的,但这里的第一个数据:连接表没有空

Table 1 
District 
-1 
3 
2 
1 
3 

Table 2 
ID  ID_Name 
1  Main 1 
2  Main 2 
3  Main 3 

如何加入表,因此它看起来像这样?

District 
-1 
Main 3 
Main 2 
Main 1 
Main 3 
+1

你能张贴到目前为止,你已经尝试了什么? – BJones

+0

'代码左外连接 \t Pubworks.dbo.District ON Pubworks.dbo.District.ID = Pubworks.dbo.csc.DistID' 结果: '区 NULL 主要3 主2 Main 1 Main 3' – tryingtolearn

+1

花点时间了解外连接:https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/左,右和全外。 – xQbert

回答

0

我假设第二列被命名为Name这一点,但你可以用COALESCE做到这一点和LEFT JOIN

Select  Coalesce(T2.Name, Str(T1.District)) As District 
From  Table1 T1 
Left Join Table2 T2 On T1.District = T2.Id 
0

假设表2有

Table 2 
ID  col2 
1  Main 1 
2  Main 2 
3  Main 3 

你可以使用左连接

select table1.Distric, table2.col2 
from table1 
left join table2 on table1.dictrict = t2.ID 
order by table2 col2 
0

您可以使用左侧加入:

Select coalesce(t2.col, t1.District) from table1 t1 
    left join table2 t2 on t1.District = t2.Id