简体   繁体   English

SQL仅在数据存在时才从其他表中选择colmn

[英]SQL Select colmn from other table only if data exist

I have two tables and I'm selecting data from the first table. 我有两个表,我要从第一个表中选择数据。 If the condition is meet(Alias type = 2) and the data in second table for the id from the first table exist the I want to select the column from the second table. 如果满足条件(别名类型= 2)并且第二张表中的数据来自第一张表的ID,则我想从第二张表中选择列。 Here is data to explain more: 以下是资料,以进一步说明:

Table 1 表格1

id | Name         | Location  
---+--------------+---------  
34 |John Smith    |NewYork  
36 |Mike Smith    |London  
45 |Bob Smith     |Los Angeles  

Table 2 表2

id | Alias             | Alias type     
---+-------------------+-------  
36 |Warren Johnson     |1  
36 |William Williams   |2  

Wanted results if alias type = 2 别名类型= 2时所需的结果

id |Name               | Location   
---+-------------------+---------  
34 |John Smith         |NewYork  
36 |William Williams   |London  
45 |Bob Smith          |Los Angeles  

Can you help me write query to get the wanted results? 您能帮我写查询以获得所需结果吗? Tell me if I need to explain more. 告诉我是否需要解释更多。 I'm using a SQL Server database. 我正在使用SQL Server数据库。

You can use a left outer join onto Table2, and then COALESCE the Alias and Name results like this: 您可以在Table2上使用left outer join联接,然后使用别名和名称结果进行COALESCE ,如下所示:

SELECT Table1.ID, COALESCE(Table2.Alias, Table1.Name) AS Name, 
    Table1.Location
FROM Table1
LEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID AND Table2.AliasType = 2

COALESCE works by finding the first non-null value in the supplied values. COALESCE通过在提供的值中找到第一个非空值来工作。

Try something like this -- you just need to use CASE : 尝试这样的事情-您只需要使用CASE

SELECT T1.Id, 
   CASE WHEN T2.Alias IS NOT NULL THEN T2.Alias ELSE T1.Name END as Name,
   t1.Location
FROM Table1 T1
   LEFT JOIN Table2 T2 ON T1.Id = T2.Id AND T2.AliasType = 2

Here is the SQL Fiddle . 这是SQL Fiddle

Good luck. 祝好运。

The COALESCE function will let you have a fall-back expression so that the name from table 2 is used if it exists, and the name from table 1 is used otherwise. COALESCE函数将使您拥有一个后备表达式,以便使用表2中的名称(如果存在),否则使用表1中的名称。 The LEFT outer join only joins table 2 when the rows exist, and t2.name is null if no record was joined. LEFT外部联接仅在存在行时联接表2,如果没有联接记录,则t2.name为null。

SELECT t1.id, COALESCE(t2.name, t1.name), t1.location FROM [Table 1] as t1 LEFT JOIN [Table 2] as t2 on t1.id=t2.id and t2.[alias type]=2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM