2014-01-05 56 views
0

我有數據,像這樣的表:SQL更新導致

-------------+-------------+------- 
| foo_date | description | flag | 
-------------+-------------+------- 
| 2014-01-01 | asdf 123 | 1 | 
-------------+-------------+------- 
| 2014-01-01 | FOO   | 1 | 
-------------+-------------+------- 
| 2014-01-02 | asdf 456 | 1 | 
-------------+-------------+------- 

我試圖將標誌設置爲0的任何行,其中的描述是不是「foo」和有在同一天的一行是「FOO」。因此,在此示例數據集中,第一行將獲得標誌= 0,因爲同一日期有一個FOO,但第三行不會因爲該日期沒有匹配的FOO。以下是我提出的那些作品,但它並不覺得這是最有效的方法。

UPDATE 
    foo_table t1 
JOIN 
(
    SELECT 
    * 
    FROM 
    foo_table 
    WHERE 
    (foo_date) IN 
    (
     SELECT 
     foo_date 
     FROM 
     foo_table 
     WHERE 
     description LIKE 'FOO%' 
    ) 
    AND description NOT LIKE 'FOO%' 
) AS t2 
ON 
(
    t1.foo_date = t2.foo_date 
    AND t1.description = t2.description 
) 
SET 
    t1.flag = 0 
+0

工作的呢?如果是這樣,這似乎是[codereview.se]的問題。 – hichris123

+0

您正在使用哪些DBMS? –

+0

@a_horse_with_no_name:現在的MySQL,以後可能還有別的東西(不是MSSQL) – fwrawx

回答

0
update t1 
set t1.flag = 0 
from foo_table t1 
where  t1.description <> 'FOO' 
     and exists (select * 
        from foo_table t2 
        where  t2.foo_date=t1.foo_date 
         and t2.description = 'FOO') 
0

根據您的數據,這可能是更有效的:

update t1 
set t1.flag = 0 
from foo_table t1 
where isnull(t1.description,'') <> 'FOO' 
and t1.foo_date in (select t2.foo_date 
        from foo_table t2 
        where t2.description = 'FOO')