postgresql 中的 if 语句
if
语句通过返回真或假值来评估条件。我们可以使用它来执行基于条件的查询。
本文将教我们如何编写 if
语句查询,并了解条件语句在开发后端应用程序时如何帮助我们。
在 postgresql 中使用 if
语句编写查询以执行不同的操作
使用以下命令登录 postgresql 服务器。在返回的提示中输入密码并回车。
david@david-hp-probook-6470b:~/documents/work/upwork/jhinku-tutorials$ psql -u postgres
password for user postgres:
默认用户 postgres 有一个名为 postgres 的数据库,我们需要创建我们的数据库,我们将使用它来测试我们的 if 语句查询。
postgres=#
使用以下命令创建一个新数据库:
postgres=# create database if_statement_db;
create database
要从 postgres 数据库转移到 if_statement_db,请使用下面提供的命令并注意我们以用户 postgres 连接到新数据库。
postgres=# \c if_statement_db;
you are now connected to database "if_statement_db" as user "postgres".
if_statement_db=#
创建一个名为 phone 的表,其中包含字段 id、phone_name、phone_color 和 phone_price。使用下面提供的数据定义查询。
if_statement_db=# create table phone(
if_statement_db(# id serial unique not null,
if_statement_db(# phone_name varchar(50),
if_statement_db(# phone_type varchar(50),
if_statement_db(# phone_price integer,
if_statement_db(# primary key(id));
create table
在电话表中插入一些记录。这些记录将帮助我们执行条件 if 语句查询。
if_statement_db=# insert into phone(phone_name, phone_type, phone_price)
if_statement_db-# values('sumsung a7', 'refurbished',600);
insert 0 1
if_statement_db=# insert into phone(phone_name, phone_type, phone_price)
if_statement_db=# values('motorola', 'new',800);
insert 0 1
if_statement_db=# insert into phone(phone_name, phone_type, phone_price)
if_statement_db=# values('iphone 10', 'new',700);
insert 0 1
在你的机器上创建一个文件并将其命名为 data.sql 或你喜欢的任何名称。编写要针对此文件中的电话表执行的 if 语句查询。
示例(data.sql):
do
$do$
begin
if exists(select * from phone) then
delete from phone;
else
insert into phone(phone_name, phone_type, phone_price)
values('sumsung a7', 'refurbished',600);
insert into phone(phone_name, phone_type, phone_price)
values('motorola', 'new',800);
insert into phone(phone_name, phone_type, phone_price)
values('iphone 10', 'new',700);
end if;
end
$do$
我们的查询将检查表中是否存在任何记录。如果存在记录,这些记录将从表中删除。
如果表没有任何记录,则查询插入新记录。
使用以下命令执行 data.sql 文件。由于我们的表包含一些值,我们应该期望执行删除操作,因为 if 条件将评估为真。
if_statement_db=# \i /home/david/documents/work/upwork/jhinku-tutorials/data.sql;
do
检索数据库中所有值的查询返回零记录。
if_statement_db=# select * from phone;
输出:
id | phone_name | phone_type | phone_price
---- ------------ ------------ -------------
(0 rows)
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
在一个 postgresql 查询中使用多个 with 语句
发布时间:2023/03/20 浏览次数:337 分类:postgresql
-
在本教程中,我们将学习如何使用多个 with 语句在 postgresql 中使用两个临时表执行查询。
发布时间:2023/03/20 浏览次数:185 分类:postgresql
-
本文介绍如何在 ubuntu 上找到 postgresql 数据库的配置文件。
发布时间:2023/03/20 浏览次数:409 分类:数据库
-
本文解释了如何直接从终端/命令行或 psql shell 运行 sql 文件。为此,你需要指定主机名、端口、用户名和数据库名称。
发布时间:2023/03/20 浏览次数:89 分类:postgresql
-
本文展示了如何列出 postgresql 上的活动连接。
发布时间:2023/03/20 浏览次数:966 分类:postgresql
-
在 pl/sql 中,你可能需要在 postgres 中使用循环。我们可以使用 for 和 while 语句来创建循环。
发布时间:2023/03/20 浏览次数:141 分类:postgresql
-
本文介绍如何在 postgresql 中仅使用单个查询来重命名列以及更改其类型。
发布时间:2023/03/20 浏览次数:233 分类:postgresql
-
本文介绍如何在 postgresql 中使用 select 方法连接列。
发布时间:2023/03/20 浏览次数:281 分类:postgresql
-
本文展示了如何使用 case 语句并给出了 postgresql 中的示例。