将列复制到具有重复值的另一行

时间:2015-05-25 08:13:38

标签: sql sql-server

我有一张看起来像这样的表。

ID   Name    Country  Published
1    Madrid           0
2    Madrid  Spain    1
3    Paris   France   0
4    London  England  0

在名称相同的任何情况下,我都需要将Country从Published = 1条目复制到Published = 0条目。我这样做是这样的:

UPDATE mytable SET Country=(SELECT Country FROM mytable  WHERE ID = 2) WHERE ID=1

但是有没有办法自动执行此操作而不是手动浏览每一个条目?

4 个答案:

答案 0 :(得分:6)

通过加入来实现:

{
 "page_1"=>[
     {:price=>"40 €", :price_per_day=>"40 €", :provider1=>"XX"}, 
     {:price=>"43 €", :price_per_day=>"43 €", :provider1=>"XX"}
   ],
  "page_2"=>[
     {:price=>"40 €", :price_per_day=>"40 €", :provider1=>"XX"}, 
     {:price=>"43 €", :price_per_day=>"43 €", :provider1=>"XX"}
   ]
 }

输出:

DECLARE @t TABLE
    (
      ID INT ,
      Name VARCHAR(20) ,
      Country VARCHAR(20) ,
      Published BIT
    )

INSERT  INTO @t
VALUES  ( 1, 'Madrid', NULL, 0 ),
        ( 2, 'Madrid', 'Spain', 1 ),
        ( 3, 'Paris', 'France', 0 ),
        ( 4, 'London', 'England', 0 )


UPDATE t1 SET Country = t2.Country
FROM @t t1
JOIN @t t2 ON t1.Name = t2.Name AND t2.Published = 1
WHERE t1.Country IS NULL AND t1.Published = 0

SELECT * FROM @t

答案 1 :(得分:0)

if( $num_row > 0 ) {
    $_SESSION['id']=$row['user_id'];
    header('location:index.php');
}

答案 2 :(得分:0)

尝试以下代码。希望它能帮到你

</body>

答案 3 :(得分:0)

在您的查询中,您只需更改ID引用以匹配基于Name的相关子查询,并为PublishedCountry添加过滤器

UPDATE t
SET Country = (SELECT TOP 1 Country FROM t t2 WHERE t2.Name = t.Name AND Published = 1 ORDER BY Country)
WHERE Published = 0
AND Country IS NULL;

SQL Fiddle