使用选择多个表更新数据库行

时间:2018-08-02 10:21:53

标签: sql postgresql

我有这些表和值:

Table1                 Table2                
------------------     --------              
ID | CREATED_BY        ID | NAME                   
------------------     --------              
1 |                    1  | aaa                  
2 |                    2  | bbb                   
3 |                    3  | ccc
4 |                    4  | ddd                    


Table1_2_link                                       
--------------------------                     
ID | TABLE1_ID | TABLE2_ID                                   
--------------------------                     
1 |  1         |   1                                
2 |  2         |   2                                  
3 |  3         |   3                        
4 |  3         |   4

我想用表2中的名称值更新表1中的created_by列,其中表1_2_link只有一对(表1_ID,表2_ID)。

更新后的结果必须为:

Table1             
------------------ 
ID | CREATED_BY    
------------------ 
1 |  aaa           
2 |  bbb           
3 |                
4 |                

是否可以通过简单的SQL查询来做到这一点?

2 个答案:

答案 0 :(得分:0)

您需要joinupdate

update table1 t1
    set created_by = t2.name
    from (select t12.TABLE1_ID, max(t12.TABLE2_ID) as TABLE2_ID
          from Table1_2_link t12
          group by t12.TABLE1_ID
          having count(*) = 1
         ) t12 join
         table2 t2
         on t12.TABLE2_ID = t2.id
    where t12.TABLE1_ID = t1.id;

Table1_2_link上的子查询查找仅具有一行的ID。当只有一行时,MAX()返回该行中TABLE2_ID的值。

答案 1 :(得分:0)

请在下面的查询中尝试:

 <ul style="list-style:none;">
            <?php $i = 0; while($row = $result->fetch_assoc()):?>

                <li class="list-group-item" data-index="$i" ><?=$row['name']?><li>

            <?php $i++ ; endwhile ?>
        </ul>


$('ul li').click(function() {
    var index = $(this).data('index');
    console.log(index);
})
相关问题