我通过连接使用两个表进行选择。我需要使用第二个表字段更新第一个表。选择如下
ActiveRecord::Schema.define(version: 20150709110928) do
create_table "author_books", id: false, force: :cascade do |t|
t.integer "author_id"
t.integer "book_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "author_books", ["author_id"], name:
"index_author_books_on_author_id"
add_index "author_books", ["book_id"],
name:"index_author_books_on_book_id"
create_table "authors", force: :cascade do |t|
t.string "name"
t.string "surname"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "books", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
我如何更新对应于Table1的相同选择(SET R.f2 = Z.f2)?
select R.f1, Z.f2,R.f3
FROM
(select * From Table1 where f2<>'xx' and f3='z') R inner join
(select * From Table2 where f3='xx') Z
ON R.f1⁼Z.f1 and R.f4=Z.f4
当我尝试时,我收到了回复
UPDATE的目标表R不可更新
答案 0 :(得分:1)
您可以使用以下内容在update
语句中使用联接....
update t
set t.Column = value
from Table t
inner join OtherTable ot on t.Id = ot.TID
where somecondition = true.
答案 1 :(得分:1)
您应该在table1
上执行更新并将其加入第二个子查询。第一个子查询中table1
的条件可以应用于where子句:
UPDATE table1 r
JOIN (SELECT * FROM table2 WHERE f3 = 'xx') z ON r.f1 ⁼ z.f1 AND r.f4 = z.f4
SET r.f2 = z.f2
WHERE r.f2 <> 'xx' AND r.f3 = 'z'