如果计数大于零则更新,否则不做任何事情

时间:2019-04-06 11:53:27

标签: sql postgresql

我有两个查询,首先是检查table1中是否存在值,如果是-我正在更新table2中的值,否则我返回0作为找到的值的计数。 / p>

它确实经常发生,我希望我可以通过一个查询来做到这一点。查询的样子如何?

2 个答案:

答案 0 :(得分:1)

您可以加入table1和table2,然后使用table1更新table2中的值。

答案 1 :(得分:1)

也许您可以尝试类似的方法。如果d2 = { "items": { "item": [ { "id": "0001", "type": "donut", "name": "Cake", "ppu": 0.55, "batters": { "batter": [ {"id": "1001", "type": "Regular"}, {"id": "1002", "type": "Chocolate"}, {"id": "1003", "type": "Blueberry"}, {"id": "1004", "type": "Devil's Food"} ] }, "topping": [ {"id": "5001", "type": "None"}, {"id": "5002", "type": "Glazed"}, {"id": "5005", "type": "Sugar"}, {"id": "5007", "type": "Powdered Sugar"}, {"id": "5006", "type": "Chocolate with Sprinkles"}, {"id": "5003", "type": "Chocolate"}, {"id": "5004", "type": "Maple"} ] }, ... ] } } pprint.pprint(search(d2, '500', ['d2'])) >> [[[[[[[['d2', 'items', 'item', 0, 'topping', 0, 'id', '5001']]], [[['d2', 'items', 'item', 0, 'topping', 1, 'id', '5002']]], [[['d2', 'items', 'item', 0, 'topping', 2, 'id', '5005']]], [[['d2', 'items', 'item', 0, 'topping', 3, 'id', '5007']]], [[['d2', 'items', 'item', 0, 'topping', 4, 'id', '5006']]], [[['d2', 'items', 'item', 0, 'topping', 5, 'id', '5003']]], [[['d2', 'items', 'item', 0, 'topping', 6, 'id', '5004']]]]]]]] 子句中至少更新了一行,则RETURNING子句将返回行。然后通过with部分中的exists检查来对其进行验证。

select

此查询在运行时将在没有行存在时返回with upd as ( update table2 t2 set col = 'value4' where id = ? and exists ( select 1 from table1 t1 where id = ? ) returning * ) select exists ( select 1 from upd ) :: int as "updated"; (等于布尔值0的整数),并在至少更新一行时返回false

DEMO