我想有一个包含值来比较表和操作员使用(=,!=,~,!~等).例如:
CREATE TABLE rule (
value1 varchar NOT NULL,
op1 varchar NOT NULL,
value2 varchar NOT NULL,
op2 varchar NOT NULL,
...
);
Run Code Online (Sandbox Code Playgroud)
我想要的可以使用这个伪代码来描述:
SELECT * FROM rule WHERE value1 op1 ?;
Run Code Online (Sandbox Code Playgroud)
在示例中,我将操作符存储在单独的列中,但我对其他解决方案持开放态度.
使用Postgres我有一个有conversations和的模式conversationUsers.每个conversation都有很多conversationUsers.我希望能够找到具有确切指定数量的对话conversationUsers.换句话说,提供了一个userIds(例如[1, 4, 6])我希望能够找到仅包含那些用户的对话的数组,而不是更多.
到目前为止,我试过这个:
SELECT c."conversationId"
FROM "conversationUsers" c
WHERE c."userId" IN (1, 4)
GROUP BY c."conversationId"
HAVING COUNT(c."userId") = 2;
Run Code Online (Sandbox Code Playgroud)
不幸的是,这似乎也回归了包括这两个用户在内的对话.(例如,如果对话还包括"userId"5 ,则返回结果).
我在 Postgres 9.5中t有一个带有数组列的表z。我想选择id其中z要么是NULLOR {NULL}。
id | z
---+--------
1 | {NULL}
2 | null
Run Code Online (Sandbox Code Playgroud)
我试图改变{NULL}到NULL以array_remove():
SELECT id,
array_remove(z,NULL) as removed
from t;
Run Code Online (Sandbox Code Playgroud)
返回:
id | z | removed
---+--------+-------
1 | {NULL} | {}
2 | null | null
Run Code Online (Sandbox Code Playgroud)
但是,如果我查询这个:
select id, z from t where removed is null;
Run Code Online (Sandbox Code Playgroud)
我仍然得到 id 1。理想情况下,我想避免取消嵌套和分组备份。
days函数中的参数getAvgByDay()不起作用,我猜是因为它在引号内:
CREATE OR REPLACE FUNCTION getAvgByDay(days int)
RETURNS TABLE ( average text,
date timestamp with time zone
) AS
$func$
BEGIN
RETURN QUERY
SELECT to_char( AVG(measure), '99999D22') AS average, ( now() - interval '$1 day') AS date
FROM (
SELECT mes.date, mes.measure
FROM measures mes
WHERE mes.date < ( now() - interval '$1 day')
) AS mydata;
END
$func$
LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud) 我有一个看起来像这样的数组[[(Double,Double)]]。它是一个多维元组数组。
这是我永远不会查询的数据,因为它不需要查询。只有在客户端是这样才有意义。我正在考虑将整个内容存储为字符串,然后将其解析回多数组。
这是一个很好的方法吗?考虑到我最多可以有 20 个数组,其中最多有 4 个内部数组,每个数组都有一个 2 Double 的元组,那么解析会非常昂贵吗?
我如何检查哪种方法更好,以及将其存储为 PostgreSQL 中的多维数组是否是更好的方法?
我将如何存储它?
postgresql parsing database-design tuples multidimensional-array
我想创建一个函数,尝试将一组值转换为用户指定的类型(默认为文本)。一个非常简单的函数如下所示:
CREATE OR REPLACE FUNCTION cast_to(variable jsonb, key text, target_type anyelement DEFAULT 'TEXT'::regtype) RETURNS anyelement as $$
begin
RETURN CAST(variable->>key AS target_type);
end
$$
language plpgsql;
Run Code Online (Sandbox Code Playgroud)
我已经尝试过以下方法:
SELECT CAST('foo' AS 'text');: 给出语法错误SELECT CAST('foo' AS 'text'::regtype);: 与 1 相同的错误SELECT CAST('foo' AS pg_typeof(null::text));说type pg_typeof does not exist 最后一次尝试是我可以传入一个具有目标类型的变量而不是文本表示形式。使用该函数将如下所示SELECT cast_to('text', NULL::text);。
如何实现这个或类似的功能?
编辑:正如评论中所建议的,我尝试使用动态 SQL。我运气不太好。我创建了一个非常基本的案例,不使用任何变量:
CREATE OR REPLACE FUNCTION audit.cast_to() RETURNS text as $$
DECLARE
_sql TEXT := 'SELECT CAST($1 AS $2)';
out TEXT;
begin …Run Code Online (Sandbox Code Playgroud) 问题实际上是关于 sql 查询的优化。假设我们有这样定义的表。
CREATE TYPE record_type AS ENUM (
'TRANSFER',
'TRADE',
'VOUCHER'
);
CREATE TYPE record_status AS ENUM (
'NEW',
'VALIDATED',
'EXPIRED'
);
CREATE TABLE good_records (
id uuid PRIMARY KEY,
user_id uuid NOT NULL,
type record_type NOT NULL,
status record_status NOT NULL,
amount numeric(36,18) NOT NULL DEFAULT 0,
expired_at timestamp WITH TIME ZONE NOT NULL,
notification_sent boolean DEFAULT false,
);
Run Code Online (Sandbox Code Playgroud)
我想每 10 分钟运行一次过期检查,即我会运行SELECT * FROM good_records
where record_status = 'NEW' and notification_sent = false(和SELECT * FROM …
我有一个users包含字段id和 的表email。id是主键并且email也被索引。
database> \d users
+-----------------------------+-----------------------------+-----------------------------------------------------+
| Column | Type | Modifiers |
|-----------------------------+-----------------------------+-----------------------------------------------------|
| id | integer | not null default nextval('users_id_seq'::regclass) |
| email | character varying | |
+-----------------------------+-----------------------------+-----------------------------------------------------+
Indexes:
"users_pkey" PRIMARY KEY, btree (id)
"index_users_on_email" UNIQUE, btree (email)
Run Code Online (Sandbox Code Playgroud)
如果我在子查询中使用子句查询表,distinct on (email)我会得到显着的性能损失。
database> \d users
+-----------------------------+-----------------------------+-----------------------------------------------------+
| Column | Type | Modifiers |
|-----------------------------+-----------------------------+-----------------------------------------------------|
| id | integer | not null default nextval('users_id_seq'::regclass) |
| …Run Code Online (Sandbox Code Playgroud) postgresql performance greatest-n-per-group distinct-on postgresql-performance
我尝试执行事务操作并故意抛出异常,以验证回滚是否已完成,但回滚并未执行。
PostgreSQL 数据库版本为 12.1-1,基于 Docker。
这是包含注释的服务@Transactional:
@Service
public class MyTestService {
@Autowired
private DocumentDataDao documentDataDao;
@Transactional
public void test() {
DocumentData data = new DocumentData();
data.setData(UUID.randomUUID().toString());
documentDataDao.create(data);
throw new IllegalArgumentException("Test rollback");
}
}
Run Code Online (Sandbox Code Playgroud)
该create函数使用 aNamedParameterJdbcTemplate插入数据:
String statement = String.format("INSERT INTO %s (%s) VALUES (%s) RETURNING %s", tableName,
String.join(",", insertingColumns), String.join(",", values),
String.join(",", returningColumns));
return getNamedJdbcTemplate().queryForObject(statement, parameters, getRowMapper());
Run Code Online (Sandbox Code Playgroud)
该test函数是从另一个服务调用的:
@Service
public class ApplicationStartupListener {
private Logger log = LoggerFactory.getLogger(ApplicationStartupListener.class);
@Autowired
private MyTestService testService; …Run Code Online (Sandbox Code Playgroud) 给定一个表:
CREATE TABLE IF NOT EXISTS test."TestCounter"
("id" TEXT PRIMARY KEY,
"count" INTEGER);
Run Code Online (Sandbox Code Playgroud)
我想插入一条记录并增加计数器(如果该记录已存在)
CREATE TABLE IF NOT EXISTS test."TestCounter"
("id" TEXT PRIMARY KEY,
"count" INTEGER);
Run Code Online (Sandbox Code Playgroud)
目前我收到此错误:
ERROR: column reference "count" is ambiguous
LINE 4: SET "count" = "count" + 1
^
SQL state: 42702
Character: 107
Run Code Online (Sandbox Code Playgroud) postgresql ×10
sql ×6
dynamic-sql ×2
plpgsql ×2
arrays ×1
distinct-on ×1
function ×1
indexing ×1
java ×1
null ×1
parsing ×1
performance ×1
polymorphism ×1
sequelize.js ×1
spring-boot ×1
transactions ×1
tuples ×1
upsert ×1
where-clause ×1