Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ ビュー | トリガー、ウィンドウ関数、DCL
SQL最適化とクエリ機能

bookビュー

メニューを表示するにはスワイプしてください

前の章では、ユーザー権限について説明する際に ビュー というオブジェクトに触れました。ここでは、このオブジェクトについてさらに詳しく見ていきます。

SQLにおける ビュー とは、SQLクエリの結果セットに基づく 仮想テーブル です。ビューは実際のテーブルと同様に行と列を持ち、ビュー内のフィールドはデータベース内の1つまたは複数の実テーブルのフィールドです。 ビューは、複雑なクエリの簡素化特定データへのアクセス制限によるセキュリティ強化、およびデータを特定の形式で表示するなど、さまざまな目的で使用されます。

ビューの主な特徴

  • 仮想テーブル: ビューは物理的にデータを保存しません。基になるテーブル(ベーステーブル)からデータを取得します。
  • 複雑なクエリの簡素化: ビューを使うことで複雑なSQLクエリを1つのビューにまとめることができ、複雑な結合や集計の操作が容易になります。
  • セキュリティ: ビューを利用することで、特定の行や列へのアクセスを制限でき、セキュリティを強化できます。ユーザーにはベーステーブルへの権限を与えずに、ビューへのアクセス権のみを付与できます。
  • 一貫性: ビューは、基になるデータベーススキーマが変更されても、一貫したインターフェースを提供できます。

実装

account_activity_viewBankAccounts テーブルに基づいて、口座番号、口座名義人名、残高、および口座に対して行われた最新の操作を表示する UserLogs というビューを作成します。

1234567891011121314151617181920212223242526
-- Create a view that shows account details along with their latest action CREATE OR REPLACE VIEW account_activity_view AS SELECT ba.account_number, -- Select the account number from the bankaccounts table ba.account_holder, -- Select the account holder's name from the bankaccounts table ba.balance, -- Select the balance from the bankaccounts table ul.action AS latest_action, -- Select the latest action from the userlogs table (alias as latest_action) ul.timestamp AS latest_action_time -- Select the timestamp of the latest action (alias as latest_action_time) FROM BankAccounts ba -- Main table: bankaccounts LEFT JOIN ( -- Subquery to get the most recent action for each account SELECT DISTINCT ON (account_number) account_number, -- Select the account number action, -- Select the action timestamp -- Select the timestamp FROM UserLogs ORDER BY account_number, -- Order by account number timestamp DESC -- Order by timestamp in descending order to get the latest action ) ul ON ba.account_number = ul.account_number; -- Join the subquery result with bankaccounts on account number -- Get data from the view SELECT * FROM account_activity_view;
copy

このビューを利用することで、複雑な結合クエリを毎回作成することなく、作成済みのビューを通常のテーブルのように他のクエリで使用可能。

Note
注意

ビューは通常のテーブルのように利用できるが、実際には物理的なテーブルではない。 ビュー内のデータはディスクに保存されていない。ビューを使用するたびに、そのクエリが実行され、結果データがメインクエリで利用される。

question mark

次のうち、ビューのセキュリティ面を最もよく表している説明はどれですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  6

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  6
some-alt