Return 一个 SQL 视图中三个 SQL 查询的结果

Return result of three SQL queries in one SQL view

是否可以在一个视图中 return 三个单独 SQL 查询的结果?

我想创建一个“初始数据”视图,其中包含来自我的数据库的一些统计信息,return来自不同表的三个 counts()。类似的东西:

CREATE VIEW initial AS
   SELECT count(*) AS albums_count FROM albums,
   SELECT count(*) AS artists_count FROM artists,
   SELECT count(*) AS tracks_count FROM tracks;

我不介意结果是按行还是按列。 UNION 会有点工作 - 但从性能角度来看它没有意义。

(我知道我可以只从前端执行三个单独的请求,或者将它们合并到我的后端代码中,但我使用 PostgREST 作为我的 API,我不想制作 3 个单独的“初始”在我的网站加载时请求。)

您可以合并计数并为每个计数类型添加一列,例如

   SELECT count(*) as Quantity, 'albums' as countType FROM albums union all
   SELECT count(*), 'artists' FROM artists union all
   SELECT count(*), 'tracks' FROM tracks;

如果您想要 3 列,您可以 select 它们作为派生表:

select
(SELECT count(*) FROM albums) AS albums_count, 
(SELECT count(*) FROM artists) AS artists_count,
(SELECT count(*) FROM tracks) AS tracks_count;