原文标题:8 fascinating things you probably didn’t know postgresql can do!
原文地址:https://www.enterprisedb.com/blog/8-cool-interesting-facts-things-postgresql-can-do
原文作者:thom-brown
翻译:多米爸比
本文为在postgres中执行任务提供有用的提示和快捷方式。
- 整行引用
- where比较列合并
- with硬编码表
- 自定义配置参数
- 布尔值列可以独立写
- 不费代价转换列数据类型
- 查找数据行的归属分区
- 表即类型
一、整行引用
您是否尝试过运行以下语句?
select my_table from my_table;
这看起来可能很奇怪,但它所做的是将所有列作为行类型返回单列。您为什么要这样做?好吧,您很可能已经以这种方式引用了该表:
select table_a.column, table_b.column
from table_a
inner join table_b on table_a.id = table_b.aid;
它的作用是引用整行,然后只要求单列显示每个表,这只是常见的情况。
再看下面这个示例:
select data, backup_data
from data
full join backup_data on data = backup_data
where data is null or backup_data is null;
这里我们有一个表和它的备份。如果我们想查看它们之间的差异,或者是因为我们想查看自备份以来发生了什么变化,或者想查看我们是否丢失了任何可能需要从备份中恢复的历史行,该怎么办?
为快速演示,我们将创建表并插入三行:
postgres=# create table data (id serial, person text, country text);
create table
postgres=# insert into data (person, country)
values ('tim','france'),('dieter','germany'),('marcus','finland');
insert 0 3
现在,让我们创建一个相同的表副本并将相同的数据复制到其中:
postgres=# create table backup_data (id serial, person text, country text);
create table
postgres=# insert into backup_data select * from data;
insert 0 3
我们希望两张表数据有所不同,因此我们从原始表中删除一行并添加新行到备份表中:
postgres=# delete from data where id = 2;
delete 1
postgres=# insert into data (person, country)
values ('roberto','italy');
insert 0 1
最后,让我们看看如果我们运行查询来比较表会发生什么:
postgres=# select data, backup_data
postgres-# from data
postgres-# full join backup_data on data = backup_data
postgres-# where data is null or backup_data is null;
data | backup_data
------------------- --------------------
| (2,dieter,germany)
(4,roberto,italy) |
(2 rows)
我们可以在这里看到backup_data表包含数据表中缺少的行,反之亦然。
还有这个:
postgres=# select to_jsonb(data) from data;
to_jsonb
-----------------------------------------------------
{"id": 1, "person": "tim", "country": "france"}
{"id": 3, "person": "marcus", "country": "finland"}
{"id": 4, "person": "roberto", "country": "italy"}
(3 rows)
我们将所有数据转换为json!
二、where比较列合并
这是一个非常方便的技巧,可使查询更短且更易于阅读。
假设我们有以下查询:
select country, company, department
from suppliers
where country = 'australia'
and company = 'skynet'
and department = 'robotics';
我们可以去掉那些and:
select country, company, department
from suppliers
where (country, company, department) = ('australia','skynet','robotics');
我们还可以使用in来满足or条件。如果我们调整原始查询:
select country, company, department
from suppliers
where department = 'robotics'
and (
(country = 'australia'
and company = 'skynet')
or
(country = 'norway'
and company = 'nortech')
);
我们可以将其缩短为:
select country, company, department
from suppliers
where department = 'robotics'
and (country, company) in (('australia','skynet'),('norway','nortech'));
三、with硬编码表
假设您只有对数据库及其表的读取权限,但您有一小部分数据要用于连接现有表。
select station, time_recorded, temperature
from weather_stations;
station | time_recorded | temperature
---------------- --------------------- -------------
biggin_hill_14 | 2020-02-02 13:02:44 | 22.4
reigate_03 | 2020-02-02 16:05:12 | 20.9
aberdeen_06 | 2020-02-02 15:52:49 | 8.5
madrid_05 | 2020-02-02 14:05:27 | 30.1
(4 rows)
我们想知道每个车站的温暖程度,所以我们可以构造这个查询:
select station,
case
when temperature <= 0 then 'freezing'
when temperature < 10 then 'cold'
when temperature < 18 then 'mild'
when temperature < 30 then 'warm'
when temperature < 36 then 'hot'
when temperature >= 36 then 'scorching'
end as temp_feels
from weather_stations;
如果我们设置一个伪表来包含所有这些信息,我们可以添加更多模拟的数据,并且为了更容易使用,我们可以将它放在一个公共表表达式中:
with temp_ranges (temp_range, feeling, colour) as (
values
('(,0]'::numrange, 'freezing', 'blue'),
('( 0,10)'::numrange, 'cold', 'white'),
('[10,18)'::numrange, 'mild', 'yellow'),
('[18,30)'::numrange, 'warm', 'orange'),
('[30,36)'::numrange, 'hot', 'red'),
('[36,)'::numrange, 'scorching', 'black')
)
select ws.station, tr.feeling, tr.colour
from weather_stations ws
inner join temp_ranges tr on ws.temperature <@ tr.temp_range;
注意:不熟悉范围类型的人可能会被“numrange”值和数据类型混淆。它是范围类型中的一种,用于数值范围的类型。圆括号表示排他;方括号表示包括在内。因此,’(0,10]’ 表示“从0开始但不包括0,直到并包括10”。缺失值如果是第一个值表示之前的任何值,缺失值如果是第二个值表示之后的任何值。
四、自定义配置参数
postgres有广泛的参数,允许您配置数据库系统的各个方面,但您也可以添加自己的参数并调用任何您想要的参数,只要您给它们自己的配置类。
例如,您可以将其添加到 postgresql.conf:
config.cluster_type = 'staging'
然后使用 show 命令访问它。
postgres=# show config.cluster_type;
config.cluster_type
---------------------
staging
(1 row)
请注意,这些设置不会出现在pg_settings中,也不会由show all输出。
那么为什么我们能够做到这一点呢?为什么我们不能在不提供配置前缀的情况下做到这一点?在 postgresql 9.2 之前,有一个名为custom_variable_classes的设置,它获取了一个类列表,这些类可以被扩展用于他们自己的设置。如果您想在postgresql.conf 中配置它,您需要将该扩展的类添加到列表中。但是,此要求在较新的版本中已删除,您不再需要显式声明它们。只有内置的配置参数没有前缀,所以任何自定义的参数都需要前缀,否则将不被接受。
正如您在上面的示例中所看到的,当您想要提供有关集群的某种元数据时,这可能会很方便。
五、布尔值列可以独立写
您可能编写了如下查询:
select user, location, active
from subscriptions
where active = true;
您知道您不需要那个“= true”吗?可以这样写:
where active
这是因为布尔值不需要与另一个布尔值进行比较,因为表达式无论如何都会返回 true 或 false。如果想取反的,可以写:
where not active
读起来也更好。
六、不费代价转换列数据类型
通常,当更改包含现有数据表列的类型时,必须重写整个表以将数据存储在其新数据类型中。但在很多情况下,可以避免这一情况发生。
以下语句是如何找到所有这些:
select
castsource::regtype::text,
array_agg(casttarget::regtype order by casttarget::regtype::text) casttargets
from pg_cast
where castmethod = 'b'
group by 1
order by 1;
该语句将返回一个相对较小的类型列表以及它们可以转换为的类型集,因为它们是“binary compatible”(二进制亲和的)。在此列表中,您将看到text、xml、char 和 varchar都是可以互换的–它们是相同存储的二进制格式。因此,如果您在文本列中有一个包含xml数据的表,请随意转换它而不会受到影响(请注意,如果您的数据中有无效的xml,postgres将禁止它并告诉您)。
七、查找数据行的归属分区
您可能将数据拆分为不同的分区,但是当您选择行时,如果您想知道每行来自哪个分区表怎么办?这很简单:只需将 tableoid::regclass 添加到您的 select 子句中。例如:
postgres=# select tableoid::regclass, * from customers;
tableoid | id | name | country | subscribed
-------------- ----- ---------------- ---------------- ------------
customers_de | 23 | hilda schumer | germany | t
customers_uk | 432 | geoff branshaw | united kingdom | t
customers_us | 815 | brad moony | usa | t
(3 rows)
这是有效的,因为tableoid 是一个隐藏的系统列,您只需要显式选择才能看到它。它返回该行所属表的 oid(对象标识符)。如果将其转换为regclass 类型,它将返回表名。
八、表即类型
您没听错。每当创建一个表时,您也同时创建了一个新类型:
create table books (isbn text, title text, rrp numeric(10,2));
我们可以在创建另一个表时使用此表类型,或者作为函数参数或返回类型:
create table personal_favourites (book books, movie movies, song songs);
然后,您将在其中输入信息:
insert into personal_favourites (book)
values (('0756404746','the name of the wind',9.99));
或者:
insert into personal_favourites (book.isbn, book.title, book.rrp)
values ('0756404746','the name of the wind',9.99);
要从表值中获取单个值,您可以从列中选择列:
select (book).isbn, (book).title, (book).rrp
from personal_favourites;
而且,正如我在“整行引用”中提到的,您可以将整行转换为json,它会以您希望的方式返回所有内容:
postgres=# select jsonb_pretty(to_jsonb(personal_favourites))
from personal_favourites;
jsonb_pretty
----------------------------------------------
{
"book": {
"rrp": 9.99,
"isbn": "0756404746",
"title": "the name of the wind"
},
"song": {
"album": "grace",
"title": "this is our last goodbye",
"artist": "jeff buckley"
},
"movie": {
"title": "magnolia",
"studio": "new line cinema",
"release_date": "2000-03-24"
}
}
可以使用这种功能为json 数据创建模式,以实现类似nosql 的功能,但数据具有已定义的结构。
但是等等,如果我想存储和查询所有我最喜欢的书籍、歌曲和电影,而不仅仅是一个呢?
这也可以。任何类型,包括表,都可以通过在数据类型名称后添加 [] 转换为数组。与其重新创建表,不如将列转换为数组类型,然后添加另一本书:
alter table personal_favourites
alter column book type books[] using array[book];
alter table personal_favourites
alter column movie type movies[] using array[movie];
alter table personal_favourites
alter column song type songs[] using array[song];
我们将在 book 数组中添加另一本书:
update personal_favourites
set book = book || ('1408891468','jonathan strange and mr norrell',7.99)::books;
现在我们的结果如下所示:
postgres=# select jsonb_pretty(to_jsonb(personal_favourites))
from personal_favourites;
jsonb_pretty
--------------------------------------------------------
{
"book": [
{
"rrp": 9.99,
"isbn": "0756404746",
"title": "the name of the wind"
},
{
"rrp": 7.99,
"isbn": "1408891468",
"title": "jonathan strange and mr norrell"
}
],
"song": [
{
"album": "grace",
"title": "this is our last goodbye",
"artist": "jeff buckley"
}
],
"movie": [
{
"title": "magnolia",
"studio": "new line cinema",
"release_date": "2000-03-24"
}
]
}
book的值现在包含book对象数组,并且我们的查询没有任何更改。
我希望这些技巧可以帮助您从postgres 中获得更多价值!
保持联系
从2019年12月开始写第一篇文章,分享的初心一直在坚持,本人现在组建了一个pg乐知乐享交流群,欢迎关注我文章的小伙伴进群吹牛唠嗑,交流技术,互赞文章。
如果群二维码失效可以加我微信。