PostgreSQL – 使用 WITH CHECK OPTION 子句创建可更新视图
PostgreSQL是世界上最先进的通用开源数据库。 pgAdmin 是最流行的 PostgreSQL 管理工具或开发平台。它也是一个开源开发平台。它可以在任何操作系统中使用,并且可以作为桌面应用程序或浏览器中的网络运行。
在本文中,我们将讨论:
- 使用您的操作系统配置 pgAdmin。
- 使用 WITH CHECK OPTION 子句创建可更新视图。
配置 pgAdmin :
可以从这里下载 pgAdmin。最新版本是 pgAdmin 4 v5.2。
1. Download the PostgreSQL installer from here. Choose the proper version and Windows bits of your PC.
2. After downloading, the Setup Wizard will pop up. Specify the directory. You can keep everything as default and click Next.
3. Now comes the most important part. It will ask to enter a Password. The password is really important, please keep a note of it.
4. Now select the Port Number. By default it is “5432”.
5.Click Next and then install the setup. No need to add the Stack Builder, uncheck it and click on Finish.
6. Now install pgAdmin from the link provided above.
7. After installation finishes, restart your computer to ensure pgAdmin is working.
8. Open the pgAdmin from the Start window and then it will ask for a password. You should use the same password as discussed in Step 3.
9. Now click on Server and you can easily create a database and write a query in the Query Tool.
要在 pgAdmin 中创建数据库和表以及有关查询工具的更多信息,请访问CREATE和 递归查询。
样本输入:
考虑以下ER 模型 下面为公司创建员工详细信息和部门详细信息表。
使用 WITH CHECK OPTION 子句创建可更新视图:
当我们希望通过选择某些行或列来显示表的子集时,通常会创建视图。它用于限制对原始表的访问,用户可以看到基表的子部分。有关视图及其类型的更多详细信息,请访问PostgreSQL – 创建可更新视图。
让我们总结一下在PostgreSQL – 创建可更新视图和面临的问题中讨论的创建可更新视图:
输入:
1. 部门详情
2. 员工详情
现在,让我们为 Employee 表创建一个可更新的视图。让我们为在公司“人力资源部”工作的所有员工做一个视图。
CREATE VIEW employees_hr
AS SELECT employee_id,employee_name,department_id
FROM Employee
WHERE department_id=100
因为它是一个可更新的视图,我们可以插入值,它会反映在表 Employee 中。如果新插入值的“Department_ID”等于 100 ,那么它将同时添加到 Employee Table 和 Employees_HR 视图表中,否则不会添加到此视图 HR 中,因为 WHERE 条件变为 FALSE。
现在,我们还可以通过执行如下所示的 UPDATE 查询来删除视图并使其不可见。假设我们从“HR 视图”中删除 Neha 并设置到其他某个部门,并将她的名字更改为“Nehaa”。
UPDATE employees_hr
SET
employee_name='Nehaa',
department_id=104
WHERE
employee_id=1004
/* Removing view Neha from HR by updating her name and department */
这是没有 WITH CHECK OPTION 的可更新视图中的问题。可以访问“查看 HR”的用户可以轻松修改数据,其中的更改将反映回父表。这对任何组织来说都不是一个好兆头,因为他们授予用户更改数据的访问权限。人们可以输入错误的数据,也可以更改员工的名称。因此,数据在数据库中不再安全。
因此,为了克服这个问题,我们可以使用 WITH CHECK OPTION 子句。让我们为在销售部门工作且部门 ID = 101 的员工创建另一个视图。
CREATE VIEW employees_Sales AS
SELECT * FROM Employee
WHERE department_id=101 WITH CHECK OPTION
现在,让我们尝试插入非销售部门员工的详细信息,并尝试从该视图更新记录。
因此,保持一致性并且 WITH CHECK 选项禁止用户不要插入或更新任何与创建的视图无关的数据。