在我们的应用程序中,我们有通过电子邮件地址标识的用户。每个用户都可以为我们的应用程序的各个页面存储一系列设置。我正在尝试使用直接SQL Update查询将一个页面的设置从一个用户复制到另一个用户。数据存储在Postgresql中。
到目前为止,我有这个: -
UPDATE user_settings SET value=adminuser.value FROM (
SELECT value FROM user_settings
INNER JOIN users ON users.id=user_settings.user_id
WHERE users.emailaddress='joe@foo.com' AND user_settings.page='test'
) adminuser
WHERE user_id=60 AND page='test';
显而易见的问题是要更新的user_id是硬编码的。我试过这个: -
UPDATE user_settings SET value=adminuser.value FROM (
SELECT value FROM user_settings
INNER JOIN users ON users.id=user_settings.user_id
WHERE users.emailaddress='joe@foo.com' AND user_settings.page='test'
) adminuser
WHERE users.emailaddress='fred@foo.com' AND user_settings.page='test';
但Postgresql不想知道。如何在表上执行连接以进行更新,以便我可以访问emailaddress字段?
答案 0 :(得分:1)
您是不是只缺少FROM列表中的表名?
UPDATE user_settings SET value=adminuser.value FROM (
SELECT value FROM user_settings usa
INNER JOIN users ua ON ua.id=usa.user_id
WHERE ua.emailaddress='joe@foo.com' AND usa.page='test'
) adminuser,
users
WHERE
users.emailaddress='fred@foo.com' AND user_settings.page='test'
AND users.id=user_settings.user_id;
(顺便说一句:如果你花时间提供SQL脚本来创建一个包含一些数据的虚拟模式来尝试它,那么获得这类问题的答案要容易得多。如果不这样做,那就更加困难和痛苦了。回答)
答案 1 :(得分:-1)
看看是否有效。
UPDATE user_settings SET value=
(select top 1 Value
from
user_settings
INNER JOIN users ON users.id=user_settings.user_id
WHERE users.emailaddress='joe@foo.com' AND user_settings.page='test'
)
WHERE user_id=60 AND page='test';