简体   繁体   中英

Updating a table from another table

I have a query down below which works. My question is I cant seem to alter it so it updates the LessonTaken field in Availability Table everytime unless StudentID=0. So only want it to update the field if the studentID <> 0;

UPDATE Availability SET LessonTaken = 'Y'
WHERE (
   SELECT LessonID
   FROM Lesson
   WHERE Availability.StudentID = Lesson.StudentID
);

The Tables are like so:

Availability:

AvailabilityID StudentID StartTime EndTime LessonTaken NoOfFrees

Lesson:

LessonID StudentID StartTime EndTime DayOfWeek LessonPaid.

I have a query which selects the student with the fewest frees, (selecting DayOfWeek, StartTime, EndTime) and inserts this into the LessonTable for the corresponding fields. This is for a timetabling programme. I hope this is clear, many thanks :)

This is for T-SQL, using join

update avail
    set LessonTaken = 'Y' 
from Availability avail
    join Lesson less on avail.StudentID = less.StudentID
where avail.StudentID <> 0

Good luck

Does adding the condition you want help?

UPDATE Availability
    SET LessonTaken = 'Y'
WHERE Availability.studentID <> 0 AND
      (SELECT LessonID
       FROM Lesson
       WHERE Availability.StudentID = Lesson.StudentID
      );

this might sound silly, but have you tried:

UPDATE Availability SET LessonTaken = 'Y'
WHERE (SELECT LessonID
       FROM Lesson
       WHERE Availability.StudentID = Lesson.StudentID
       AND Lesson.StudentID != 0 
       );

?? Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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