多対1の関係にある2つのテーブルがあります。暗黙的な結合を使用して、親テーブルの条件で「子」テーブルのアイテムを選択できます。
select * from child,parent where child.parentid=parent.id and parent.name like 'foobar%'
プレーンよりも子供を削除するためのより良い(より効率的でよりエレガントな)方法はありますか?
delete from child where child.parentid in (select id from parent where parent.name like 'foobar%')
この答えは私ができることを示唆しています:
delete child from child,parent where child.parentid=parent.id and parent.name like 'foobar%'
しかし、PostgreSql(SquirrelSQL経由)では構文エラーが発生します...もちろん、テーブル名が長いので、実際のリクエストは次のようになります。
delete c from child c, parent p where c.parentid=p.id and p.name like 'foobar%'
それで、これはPGによってサポートされていますか、それとも別の方法がありますか?
ボーナスポイント:以下を使用して2つのテーブルからアイテムを削除できますか?
delete from child,parent where child.parentid in (select id from parent where parent.name like 'foobar%')
データ変更CTEを使用して、1つのステートメントで両方のテーブルから削除できます。
with deleted_parent as (
delete from parent
where name like 'foobar%'
returning id
)
delete from child
where id in (select id from deleted_parent)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加