使用同一表中同一列的值更新一列

时间:2018-12-31 08:57:40

标签: sql postgresql postgresql-10

在postgres中,我想进行如下更新。

我的表def S_loss(y_true, y_pred): Gnoobj = 0.5 Gcoord = 5. mask = y_pred[..., 0] > 0 w_pred = tf.boolean_mask(y_pred[..., 1], mask) w_true = tf.boolean_mask(y_true[..., 1], mask) h_pred = tf.boolean_mask(y_pred[..., 2], mask) h_true = tf.boolean_mask(y_true[..., 2], mask) wmse = mean_squared_error(w_true, w_pred) hmse = mean_squared_error(h_true, h_pred) mse = wmse + hmse binary = binary_crossentropy(y_true[..., 0], y_pred[..., 0]) return Gcoord * mse + Gnoobj * binary 具有这些列

  • uuid
  • 已出售
  • product_id
  • variant_id
  • 数据

我想用具有product_id和variant_id的记录的uuid更新所有sold = true记录的uuid。

例如

如果这是我的桌子 enter image description here

我想将product_id = 203和variant_id = 1的记录更新为具有相同的uuid。并且product_id = 3242和variant_id = 3的记录具有相同的uuid,依此类推。

更新查询应如何?

更新查询应如何?即使product_id或variant_id中的任何一个为NULL ??

Postgresql版本10.3

2 个答案:

答案 0 :(得分:2)

将UPDATE与连接到同一表一起使用。如果我误解了您需要在最后两行中切换“ t”和“ f”的情况,该查询将更新其中sold ='t'的行

UPDATE product AS p 
SET uuid = p2.uuid
FROM product p2
WHERE p2.product_id = p.product_id
  AND (p2.variant_id = p.variant_id  OR p2.variant_id IS NULL OR p.variant_id IS NULL)
  AND p.sold = 't'
  AND p2.sold = 'f'

db-fiddle

答案 1 :(得分:1)

我认为product_idvariant_id都不都是NULL的情况:

update product p1 set uuid = p2.uuid from product p2
where p1.sold = 't' and p2.sold = 'f'
  and (
    (p2.product_id = p1.product_id and p2.variant_id = p1.variant_id)
    or
    (p2.product_id IS NULL and p2.variant_id = p1.variant_id)
    or
    (p2.product_id = p1.product_id and p2.variant_id IS NULL)
  )
相关问题