非常简单的例子 - 一个表,一个索引,一个查询:
CREATE TABLE book
(
id bigserial NOT NULL,
"year" integer,
-- other columns...
);
CREATE INDEX book_year_idx ON book (year)
EXPLAIN
SELECT *
FROM book b
WHERE b.year > 2009
Run Code Online (Sandbox Code Playgroud)
给我:
Seq Scan on book b (cost=0.00..25663.80 rows=105425 width=622)
Filter: (year > 2009)
Run Code Online (Sandbox Code Playgroud)
为什么它不执行索引扫描?我错过了什么?
我创建了一个 36M 行的表,列上有一个索引type:
CREATE TABLE items AS
SELECT
(random()*36000000)::integer AS id,
(random()*10000)::integer AS type,
md5(random()::text) AS s
FROM
generate_series(1,36000000);
CREATE INDEX items_type_idx ON items USING btree ("type");
Run Code Online (Sandbox Code Playgroud)
我运行这个简单的查询并期望 postgresql 使用我的索引:
explain select count(*) from "items" group by "type";
Run Code Online (Sandbox Code Playgroud)
但是查询计划器决定使用 Seq Scan 代替:
HashAggregate (cost=734592.00..734627.90 rows=3590 width=12) (actual time=6477.913..6478.344 rows=3601 loops=1)
Group Key: type
-> Seq Scan on items (cost=0.00..554593.00 rows=35999800 width=4) (actual time=0.044..1820.522 rows=36000000 loops=1)
Planning time: 0.107 ms
Execution time: 6478.525 ms
Run Code Online (Sandbox Code Playgroud)
无解释时间: 5s 979ms
我从这里 …
我有一个数据库查询,如:
SELECT
Foo,
Foo2,
some_calc as Bar,
some_other_calc as Bar2,
From
FooBar
-- some inner joins for the calcs
GROUP BY FOO
ORDER BY Bar DESC, Bar2 DESC;
Run Code Online (Sandbox Code Playgroud)
我想使用 order 查询按数据库排序,然后将FOOs组合在一起,以便第一个分组块包含FOO具有最大 Bar 的块。FOOs的第二个分组块包含秒最高的 Bar 等。
但这不起作用,因为 Postgres 不允许随机分组:
column "Bar" must appear in the GROUP BY clause or be used in an aggregate function.
我怎样才能解决这个问题?
示例数据和输出:
????????????????????????????
? FO ? Bar ? Bar 2 ?
????????????????????????????
? 6 ? 10 ? ?
? …Run Code Online (Sandbox Code Playgroud)