我想从SQL表中获取值列表,然后使用这些值中的每一个运行查询以更新同一表中的其他字段。在另一种语言中,我会为此使用for循环,但我已经读过在SQL中应该避免/不支持循环操作。
从概念上讲(显然代码无效),这正是我想要实现的目标:
my_list = SELECT item_id
FROM my_table
WHERE value = "my_value"
AND field_id = 1
for x in my_list:
UPDATE my_table
SET meta_value = "my_value"
WHERE field_id = 2
AND item_id = x
实现这一目标的正确方法是SQL吗?
答案 0 :(得分:2)
使用join语句尝试此更新:
update My_Table t
JOIN My_Table s on(t.item_id = s.item_id
and t.field_id = 2
and s.field_id = 1)
set t.meta_value = 'my_value'
where s.value = 'MY_VALUE'
答案 1 :(得分:1)
这应该可以在不使用循环的情况下工作:
UPDATE my_table
SET meta_value = "my_value"
WHERE field_id = 2 AND item_id IN
(
SELECT item_id
FROM my_table
WHERE value = "my_value"
AND field_id = 1
);
答案 2 :(得分:0)
You should be able to join the table with a subset of itself:
UPDATE my_table t1
INNER JOIN (SELECT item_id FROM my_table WHERE value = "my_value" AND field_id = 1) t2 ON t1.item_id = t2.item_id
SET t1.meta_value = "my_value"
WHERE t1.field_id = 2