我有如下表格:
语言
language_id | language_name
--------------------
1 English
2 Hindi
书
book_id | language_id | book_name
---------------------------------
1 1 Head First Java
2 1 Head First C
3 2 Head First Java
4 2 Head First C
学生
student_id | language_id | book_id
--------------------------------------
1 1 1
2 2 3
现在,我必须更新book_id
表格的Student
列,其中包含当前id
,新book_name = Head First Java
和其他图书的book_name = Head First C
值新书必须是同一种语言。
示例结果:
student_id | language_id | book_id
--------------------------------------
1 1 2
2 2 4
我正面临着编写T-SQL查询来执行此操作的问题。请帮帮我。
答案 0 :(得分:1)
认为您需要使用别名进行更新,以便在设置子查询中找到正确的语言。
update s
set s.book_id = (select book_id from book
where book_name = 'Head First C'
and language_id = s.language_id)
from student s
where s.book_id in (select book_id from book where book_name = 'Head First Java')
答案 1 :(得分:0)
你必须通过这样的任何条件。
update Student set book_id = 2 where book_id = 1
或强>
update Student set book_id = 2 where book_id = 1 and student_id = 1
答案 2 :(得分:0)
请尝试一下,它应该符合您的要求
UPDATE s SET s.book_id = b.book_id
FROM [language] l
INNER JOIN (SELECT language_id,
MAX(book_id) book_id
FROM book
GROUP BY language_id ) b ON b.language_id = l.language_id
INNER JOIN student s ON s.language_id = b.language_id
答案 3 :(得分:0)
一种方法是加入书籍和语言表,并以此为基础进行更新 如果假设Indi书的名字也用英文书写并且与英文版完全相同,那就没问题了。
但是如果您知道book_id和language_id,那么另一种方式可能是通过Student表上的几个简单的硬编码更新。
update Student set book_id = 2 where book_id = 1 and language_id = 1;
update Student set book_id = 4 where book_id = 3 and language_id = 2;