[英]SQL update using same table subquery results
我有一个这样的数据表:
-------------+-------------+-------
| foo_date | description | flag |
-------------+-------------+-------
| 2014-01-01 | asdf 123 | 1 |
-------------+-------------+-------
| 2014-01-01 | FOO | 1 |
-------------+-------------+-------
| 2014-01-02 | asdf 456 | 1 |
-------------+-------------+-------
我正在尝试将描述不为“ FOO”的任何行的标志设置为0,并且在同一日期存在一行为“ FOO”的行。 因此,在此示例数据集中,第一行将获得flag = 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
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')
根据您的数据,这可能会更有效:
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.