小编val*_*tis的帖子

PostgreSQL 中的慢查询从两列中定义的范围之间选择单行

我导入了ip2location_db11 lite 数据库的副本,其中包含 3,319,097 行,并且我希望优化数字范围查询,其中低值和高值位于表 ( ip_from, ip_to) 的不同列中。

导入数据库:

CREATE TABLE ip2location_db11
(
  ip_from bigint NOT NULL, -- First IP address in netblock.
  ip_to bigint NOT NULL, -- Last IP address in netblock.
  country_code character(2) NOT NULL, -- Two-character country code based on ISO 3166.
  country_name character varying(64) NOT NULL, -- Country name based on ISO 3166.
  region_name character varying(128) NOT NULL, -- Region or state name.
  city_name character varying(128) NOT NULL, -- City name. …
Run Code Online (Sandbox Code Playgroud)

postgresql performance execution-plan query-performance

6
推荐指数
1
解决办法
689
查看次数

使用 GROUP BY 和 HAVING 时如何避免调用函数两次?

我有一个带有父子关系表的 PostgreSQL 数据库 (9.2)。我有一个查询,用于查找具有多个父节点的节点。

以下查询有效并返回正确的结果:

SELECT node,parents FROM
(
  SELECT nr.child AS node, COUNT(nr.parent) AS parents 
  FROM node_relation nr 
  GROUP BY nr.child
) AS count WHERE parents > 1;
Run Code Online (Sandbox Code Playgroud)

结果集:

 node   | parents
--------+---------
 n21174 |       2
 n8635  |       2
(2 rows)
Run Code Online (Sandbox Code Playgroud)

表定义为:

            Table "public.node_relation"
   Column    |         Type          |   Modifiers
-------------+-----------------------+---------------
 child       | character varying(50) | not null
 parent      | character varying(50) | not null
Indexes:
    "node_relation_pkey" PRIMARY KEY, btree (child, parent)
Run Code Online (Sandbox Code Playgroud)

我重新编写了查询以不使用子选择:

SELECT child AS node, COUNT(parent) AS parents …
Run Code Online (Sandbox Code Playgroud)

postgresql performance group-by postgresql-9.2 query-performance

4
推荐指数
1
解决办法
1722
查看次数

同一列上的多个 COUNT

我有一个表 (PostgreSQL 9.6),其中包含 260 万多个与帐户标识符关联的带时间戳的行,对于任何给定的标识符,我想计算在单个查询中出现总次数以及今天的出现次数

作为参考,这与此问题中描述的表相同,但我在此处对其进行了简化以关注此特定问题:

CREATE TABLE account_test
(
  id integer NOT NULL PRIMARY KEY
);

CREATE TABLE log_test
(
  account integer NOT NULL REFERENCES account_test(id),
  event_time timestamp with time zone NOT NULL DEFAULT now()
);

CREATE INDEX account_test_idx ON log_test USING btree (account,event_time);

INSERT INTO account_test VALUES (1);
INSERT INTO account_test VALUES (2);

INSERT INTO log_test VALUES (1,'2018-01-01');
INSERT INTO log_test VALUES (1,'2018-01-02');
INSERT INTO log_test VALUES (1,'2018-01-03');
INSERT INTO …
Run Code Online (Sandbox Code Playgroud)

postgresql count postgresql-9.6

1
推荐指数
1
解决办法
7602
查看次数