使用连接表进行 sql 更新
假设我有这个 select 语句:
SELECT ut.user_id,
a.firstname,
a.surname,
u.username,
u.email_address
FROM administrators a
JOIN user_types ut JOIN users u ON a.admin_id = ut.type_id
AND u.user_id = ut.user_id AND ut.user_type = 'ADMIN';
假设我想更新 user_id = 1 行中的所有值;
我可以单独更新每个表,或者我可以创建一个像这样的视图:
CREATE OR REPLACE VIEW full_admin AS
SELECT ut.user_id,
a.firstname,
a.surname,
u.username,
u.email_address
FROM administrators a
JOIN user_types ut
JOIN users u on a.admin_id = ut.type_id
AND u.user_id = ut.user_id
AND ut.user_type = 'ADMIN'
然后我可以写:
UPDATE full_admin
SET firstname = 'blah', etc, etc
WHERE user_id = 1;
这将更新所有表中的所有行
有没有办法在不创建视图的情况下执行此操作?
类似的东西:
UPDATE (
SELECT ut.user_id,
a.firstname,
a.surname,
u.username,
u.email_address
FROM administrators a
JOIN user_types ut
JOIN users u ON a.admin_id = ut.type_id
AND u.user_id = ut.user_id
AND ut.user_type = 'ADMIN'
)
AS temp_table
SET firstname = "ALEX"
WHERE user_id = 1;
但这不起作用
Say I have this select statement:
SELECT ut.user_id,
a.firstname,
a.surname,
u.username,
u.email_address
FROM administrators a
JOIN user_types ut JOIN users u ON a.admin_id = ut.type_id
AND u.user_id = ut.user_id AND ut.user_type = 'ADMIN';
Say I wanted to update ALL values in the row where user_id = 1;
I could update EACH TABLE individually OR i could create a view like so:
CREATE OR REPLACE VIEW full_admin AS
SELECT ut.user_id,
a.firstname,
a.surname,
u.username,
u.email_address
FROM administrators a
JOIN user_types ut
JOIN users u on a.admin_id = ut.type_id
AND u.user_id = ut.user_id
AND ut.user_type = 'ADMIN'
Then I could write:
UPDATE full_admin
SET firstname = 'blah', etc, etc
WHERE user_id = 1;
And that will update all rows in all tables
Is there a way to do this WITHOUT creating a view?
Something like:
UPDATE (
SELECT ut.user_id,
a.firstname,
a.surname,
u.username,
u.email_address
FROM administrators a
JOIN user_types ut
JOIN users u ON a.admin_id = ut.type_id
AND u.user_id = ut.user_id
AND ut.user_type = 'ADMIN'
)
AS temp_table
SET firstname = "ALEX"
WHERE user_id = 1;
However that doesnt work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想同时更新管理员和用户中的列 ,那么类似这样的事情应该可以解决问题:
SET 语句部分可以作用于连接中的任何列。
(如果这就是你所问的!)
If you want to update columns in both administrators and users at once, then something like this should do the trick:
The SET statement section can work on any of the columns in the join.
(If that's what you are asking!)
当然,只有当连接的表结构可更新时,这才有效(同样的情况也适用于视图)。
Ofcourse this will only work (same thing applies to the view) if the joined table construct is updateable.
您可以编写一些脚本(PLSQL),但我不相信您可以在一个 SQL 查询中更新多个表,除非通过视图。
PLSQL功能强大,并不复杂,可以由数据库事件触发。
You may do some scripting (PLSQL) but I don't believe you may update several tables in one SQL query other than through a view.
PLSQL is powerfull and not complicated and can be triggered by database events.