如何从多个表中获取数据

时间:2016-11-10 10:55:17

标签: sql-server



    Table1
    <table>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Rate</td>
    </tr> 
    <tr>
    <td>1</td>
    <td>Tomato</td>
    <td>10</td>
    </tr> 
    <tr>
    <td>2</td>
    <td>Brinjal</td>
    <td>10</td>
    </tr> 
    <tr>
    <td>3</td>
    <td>Potato</td>
    <td>30</td>
    </tr> 
    </table></br></br>
    Table2
    <table>
    <tr>
    <td>Id</td>
    <td>New_rates</td>
    </tr> 
    <tr>
    <td>1</td>
    <td>45</td>
    </tr>   
    <tr>
    <td>2</td>
    <td>30</td>
    </tr>   

    </table>
    </br></br>
    I want my result to look like this

    <table>
    <tr>
    <td>Id</td>
    <td>Name</td>
    <td>Rate</td>
    </tr> 
    <tr>
    <td>1</td>
    <td>Tomato</td>
    <td>45</td>
    </tr> 
    <tr>
    <td>2</td>
    <td>Brinjal</td>
    <td>30</td>
    </tr> 
    <tr>
    <td>3</td>
    <td>Potato</td>
    <td>30</td>
    </tr> 
    </table>
&#13;
&#13;
&#13;

表1

Id   Name      rate
1   Tomato      10
2   Brinjal     10
3   Cucumber    30

表2

Id  New_rate
1   25

我希望我的结果像这样

id   Name     rate
1   Tomato     25
2   Brinjal    10
3   Cucumber   30

3 个答案:

答案 0 :(得分:0)

Select tb1.id,tb1.Name,tb2.New_rate from table_1 as tb1
join table_2 as tb2 on tb1.id=tb2.id

答案 1 :(得分:0)

Select table1.id, table1.name,
    IsNull(table2.new_rate, table1.rate) As rate
  From table1 
  Left Join table2 On table1.id = table2.id;

您需要在第二个表上执行LEFT OUTER JOIN,因为第二个表没有第一个表中所有行的匹配行。

然后您可以使用IsNull()函数显示表2中的值,或者如果不存在,则从表1中显示它。

答案 2 :(得分:0)

如果要使用新值更新table1,请尝试此操作

update table1 set table1.rate=IsNull(table2.new_rate,table1.rate)

from table1 Left Join table2 on table1.id = table2.id;

然后选择table1以查看结果

如果您只想选择,请尝试以下操作:

   Select table1.id, table1.name,IsNull(table2.new_rate, table1.rate) As rate
   From table1 Left Join table2 On table1.id = table2.id;