我正在将一些使用 MySQL 的工具转换为 PostgreSQL。有了这个,我遇到了很多问题,但能够找到大部分内容。我遇到问题的是 HEX()
和 UNHEX()
。我试过 encode(%s, 'hex')
和 decode(%s, 'hex')
确实停止导致我有错误,但它仍然似乎没有成功。有谁知道这些函数在 Postgres 中的等价物是什么?
这是旧的 MySQL 查询:
SELECT HEX(test_table.hash),
title,
user,
reason,
description,
url,
performed,
comment,
authenticated,
status
FROM alerts
JOIN user_responses ON test_table.hash = user_responses.hash
JOIN test_status ON test_table.hash = test_status.hash
WHERE status = %s
这是我更新后的 PostgreSQL 格式查询:
SELECT encode(test_table.hash, 'hex') as hash,
title,
user,
reason,
description,
url,
performed,
comment,
authenticated,
status
FROM test_table
JOIN user_responses ON test_table.hash = user_responses.hash
JOIN test_status ON test_table.hash = test_status.hash
WHERE status = %s
谢谢!
最佳答案
create function hex(text) returns text language sql immutable strict as $$
select encode($1::bytea, 'hex')
$$;
create function hex(bigint) returns text language sql immutable strict as $$
select to_hex($1)
$$;
create function unhex(text) returns text language sql immutable strict as $$
select encode(decode($1, 'hex'), 'escape')
$$;
select hex('abc'), hex(123), unhex(hex('PostgreSQL'));
结果:
╔════════╤═════╤════════════╗ ║ hex │ hex │ unhex ║ ╠════════╪═════╪════════════╣ ║ 616263 │ 7b │ PostgreSQL ║ ╚════════╧═════╧════════════╝
这是 PostgreSQL:一切皆有可能 :)
关于MySQL 的 HEX() 和 UNHEX() 等同于 Postgres?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44813386/