简体   繁体   English

使用同一表子查询结果的SQL更新

[英]SQL update using same table subquery results

I have a table of data like this: 我有一个这样的数据表:

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

I'm trying to set the flag to 0 for any rows where description isn't "FOO" and there is a row on the same date that is "FOO". 我正在尝试将描述不为“ FOO”的任何行的标志设置为0,并且在同一日期存在一行为“ FOO”的行。 So, in this example data set the first row would get flag = 0 because there is a FOO for the same date, but the third row wouldn't because there is no matching FOO for that date. 因此,在此示例数据集中,第一行将获得flag = 0,因为同一日期有一个FOO,但第三行则不会,因为在该日期没有匹配的FOO。 Here's what I've come up with that works but it doesn't feel like the most efficient way of doing it. 这是我想出的方法,但它并不是最有效的方法。

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
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')

Depending on your data, this may be more efficient: 根据您的数据,这可能会更有效:

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')

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

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