Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL,Postgresql:从一个表中查询多个单元格的最佳方式_Sql_Postgresql - Fatal编程技术网

SQL,Postgresql:从一个表中查询多个单元格的最佳方式

SQL,Postgresql:从一个表中查询多个单元格的最佳方式,sql,postgresql,Sql,Postgresql,有没有更好的方法来编写这组查询,以便只扫描一次表 SELECT column1 FROM table WHERE id = 1; SELECT column2 FROM table WHERE id = 2; SELECT column3 FROM table WHERE id = 3; 这个替代方案有点浪费,因为它可以获取9个单元格,而我只需要3个: SELECT column1, column2, column3 FROM table WHERE id IN (1, 2, 3); 有没有

有没有更好的方法来编写这组查询,以便只扫描一次表

SELECT column1 FROM table WHERE id = 1;
SELECT column2 FROM table WHERE id = 2;
SELECT column3 FROM table WHERE id = 3;
这个替代方案有点浪费,因为它可以获取9个单元格,而我只需要3个:

SELECT column1, column2, column3 FROM table WHERE id IN (1, 2, 3);

有没有更有效的方法可以通过扫描表格一次来精确提取我需要的3个单元格?

使用

with t as (
  select * from tablename where id in (1, 2, 3)
)
然后使用单独的select语句或union,只扫描3个获取的行:

select column1 col from t where id = 1
union all
select column2 col from t where id = 2
union all
select column3 col from t where id = 3
见 或在1行中:

select 
  (select column1 from t where id = 1) column1,
  (select column2 from t where id = 2) column2,
  (select column3 from t where id = 3) column3;

请参见

表格未被扫描。当您正在查找三行您已经知道的ID时,将使用二进制搜索从主键索引中快速获取ID。因此,表地址是从索引中获取的,行是直接从表地址中读取的。如果您查找一个未编入索引的列,则情况会有所不同

但是,将这三个查询合并起来有两个原因:

每次向DBMS发送查询时,都必须对其进行解释并构建访问计划。因此,最好发送一个查询,而不是三个查询。 假设ID 1和3的行在磁盘块x上,ID 2的行在磁盘块y上。如果同时请求所有三行,DBMS可能会通过请求1、3、2而不是1、2、3来优化磁盘访问。 组合查询是:

SELECT column1 AS col FROM table WHERE id = 1
UNION ALL
SELECT column2 AS col FROM table WHERE id = 2
UNION ALL
SELECT column3 AS col FROM table WHERE id = 3;

首先,这三个查询不一定会扫描表三次。若你们在id上有一个索引,那个么这只是索引查找

SELECT column1 FROM table WHERE id = 1;
SELECT column2 FROM table WHERE id = 2;
SELECT column3 FROM table WHERE id = 3;
如果您确实喜欢,可以将查询改为:

select (case when id = 1 then column1
             when id = 2 then column2
             when id = 3 then column3
        end)
from t
where id in (1, 2, 3);

这假设这三列具有兼容的类型。

我的第一个想法是WITH块会产生额外查询的开销。WITH块是否为3条SELECT语句增加了总体性能优势?或者3条SELECT语句在没有WITH块的情况下是否同样有效?WITH的好处是它只扫描表一次,在本例中它获取3行。那么这3行上只有3个无关紧要的select语句。这是实际的查询吗?对我来说这似乎是荒谬的…如果你没有测量它,你怎么知道它是浪费?