更新MySQL语句

时间:2012-09-26 23:47:28

标签: mysql

我有以下问题:

我正在尝试添加Comp中的每个学生。科学。部门进入一个课程,这里是关系的DDL:

所需课程的价值为('CS-001','Weekly Seminar','Comp.Sci。',0)


Department 
      (dept_name [primary key], building, budget)

Course 
      (course_id [primary key], title, dept_name, credits)

Instructor 
      (ID [primary key], name, dept_name, salary) 
      Foreign Key is dept_name references Department

Section
      (course_id [primary key], sec_id [primary key], semester [primary key], year [primary key], building, room_number, time_slot_id) 
      Foreign Key course_id references Course

Teaches 
      ( ID [primary key], course_id [primary key], sec_id [primary key], semester [primary key], year [primary key]) 
       Foreign key ID references Instructor,
Foreign Key (course_id,sec_id,semester,year) references Section

Takes 
      (ID [primary key], course_id [primary key], sec_id [primary key], semester [primary key], year [primary key], grade) 
      Foreign key(course_id,sec_id,semester,year) references section Foreign key(ID) references student

Student 
      (ID [primary key], name, dept_name, tot_cred) Foreign key(dept_name) references department

问题是我在尝试使用更新语句时遇到错误(错误是1241 Operand should have 1 column),更正了我的语法,因为它很可能是问题所在:

update takes
set ID=ID, course_id='CS-001', sec_id='1', semester='Fall', year=2009, grade=null
where
(
select distinct name, ID
from student natural join takes
where dept_name='Comp. Sci.'
);

对不起我是MySQL的新手,如果你可以指导我纠正我的语法,可能是一个比我更好的解决方案(不确定我的解决方案是否是一个解决方案)。

2 个答案:

答案 0 :(得分:1)

我不知道takes表是什么样的,但假设您正确分配它,您的WHERE语句不提供比较操作。 WHERE需要为任何给定的返回行生成true或false结果。因此,您需要在初始查询中加入student,并使用比较结果的位置。

您的问题缺少有关takesstudent表的信息,因此无法正确重写您的查询。

答案 1 :(得分:1)

您尚未在WHERE子句中指定一个列,这就是您获得Error 1241 Operand should contain 1 column(s)的原因

update takes
set ID=ID, course_id='CS-001', sec_id='1', semester='Fall', year=2009, grade=null
where
(
   select distinct name, ID
   from student natural join takes
   where dept_name='Comp. Sci.'
);

或者,加入两个表

UPDATE  takes a 
        INNER JOIN student b
            ON a.ID = b.ID 
SET     a.ID = ID, 
        a.course_id='CS-001', 
        a.sec_id='1', 
        a.semester='Fall', 
        a.`year` = 2009, 
        a.grade = 0        -- you can't set NULL value when updating a column
WHERE   b.dept_name = 'Comp. Sci.'