如何根据选择查询的结果更新表?

时间:2013-10-16 13:50:45

标签: mysql sql sql-server sql-server-2008

假设我要更新表course_main。我的初步查询是:

update course_main
set data_src_pk1 = 2
where course_id LIKE '%FA2013' and available_ind = 'N'

嗯,这会得到一些我不想更新的课程(幸运的是只有一小部分)。所以我有一个select语句来检索我想要更新的实际数据,它返回145行。

select course_id from course_main
where course_id like '%FA2013' and available_ind = 'N'
and course_id <> 'ENGL-0330-112WE-FA2013'
and course_id <> 'ENGL-0360-112WE-FA2013' 
and course_id <> 'ENGL-0390-112WE-FA2013'
and course_id <> 'ARTC-1053-128HY-CEQ113'
and course_id <> 'ARTC-1353-128HY-FA2013'
and course_id <> 'HITT-1005-005IN-CEQ113'
and course_id <> 'HITT-1305-005IN-FA2013'
and course_id <> 'HITT-1305-006IN-FA2013'
and course_id <> 'READ-0300-104WE-FA2013'
and course_id <> 'READ-0340-104WE-FA2013'
and course_id <> 'READ-0370-104WE-FA2013'
and course_id <> 'WBCT-1003-011IN-FA2013'
and course_id <> 'WBCT-1005-011IN-CEQ113'
and course_id <> 'WBCT-1003-010IN-FA2013'
and course_id <> 'WBCT-1005-010IN-CEQ113'
and course_id <> 'ARTS-1301-012IN-FA2013'
order by course_id asc

我想使用更新语句仅查看第二个查询的145个结果。有关如何实现这一目标的任何指示?

谢谢。

3 个答案:

答案 0 :(得分:3)

怎么样

UPDATE course_main
SET data_src_pk1 = 2
WHERE course_id LIKE '%FA2013' 
   AND available_ind = 'N'
   AND course_id NOT IN ('ENGL-0330-112WE-FA2013','ENGL-0360-112WE-FA2013',.....)
 ORDER BY course_id ASC;

答案 1 :(得分:2)

update course_main
set data_src_pk1 = 2
where course_id in (select course_id from course_main
where course_id like '%FA2013' and available_ind = 'N'
and course_id <> 'ENGL-0330-112WE-FA2013'
and course_id <> 'ENGL-0360-112WE-FA2013' 
and course_id <> 'ENGL-0390-112WE-FA2013'
and course_id <> 'ARTC-1053-128HY-CEQ113'
and course_id <> 'ARTC-1353-128HY-FA2013'
and course_id <> 'HITT-1005-005IN-CEQ113'
and course_id <> 'HITT-1305-005IN-FA2013'
and course_id <> 'HITT-1305-006IN-FA2013'
and course_id <> 'READ-0300-104WE-FA2013'
and course_id <> 'READ-0340-104WE-FA2013'
and course_id <> 'READ-0370-104WE-FA2013'
and course_id <> 'WBCT-1003-011IN-FA2013'
and course_id <> 'WBCT-1005-011IN-CEQ113'
and course_id <> 'WBCT-1003-010IN-FA2013'
and course_id <> 'WBCT-1005-010IN-CEQ113'
and course_id <> 'ARTS-1301-012IN-FA2013') 

答案 2 :(得分:1)

我认为你过于复杂了。

update course_main
set data_src_pk1 = 2
where course_id like '%FA2013' and available_ind = 'N'
and course_id <> 'ENGL-0330-112WE-FA2013'
and course_id <> 'ENGL-0360-112WE-FA2013' 
and course_id <> 'ENGL-0390-112WE-FA2013'
and course_id <> 'ARTC-1053-128HY-CEQ113'
and course_id <> 'ARTC-1353-128HY-FA2013'
and course_id <> 'HITT-1005-005IN-CEQ113'
and course_id <> 'HITT-1305-005IN-FA2013'
and course_id <> 'HITT-1305-006IN-FA2013'
and course_id <> 'READ-0300-104WE-FA2013'
and course_id <> 'READ-0340-104WE-FA2013'
and course_id <> 'READ-0370-104WE-FA2013'
and course_id <> 'WBCT-1003-011IN-FA2013'
and course_id <> 'WBCT-1005-011IN-CEQ113'
and course_id <> 'WBCT-1003-010IN-FA2013'
and course_id <> 'WBCT-1005-010IN-CEQ113'
and course_id <> 'ARTS-1301-012IN-FA2013'