PostgreSQL从多个表中删除多行 [英] Postgresql delete multiple rows from multiple tables

查看:269
本文介绍了PostgreSQL从多个表中删除多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑2个或更多表:

users (id, firstname, lastname)
orders (orderid, userid, orderdate, total)

我希望删除所有用户和他们的<与名字 Sam 匹配的 strong订单。在mysql中,我通常会做左连接。在此示例中,我们未知userid。

I wish to delete all users and their orders that match first name 'Sam'. In mysql, I usually do left join. In this example userid is unknown to us.

查询的正确格式是什么?

What is the correct format of the query?

推荐答案

http://www.postgresql.org /docs/current/static/sql-delete.html

DELETE 
FROM orders o
USING users u
WHERE o.userid = u.id
  and u.firstname = 'Sam';

DELETE 
FROM users u
WHERE u.firstname = 'Sam';

您也可以使用 ON删除级联创建表

http://www.postgresql.org/docs/current/static/ddl-constraints.html

CREATE TABLE order_items (
    product_no integer REFERENCES products ON DELETE RESTRICT,
    order_id integer REFERENCES orders ON DELETE CASCADE,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);

这篇关于PostgreSQL从多个表中删除多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆