我正在把一些使用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'));
Result:-9556;-95252;-9552;-9552;-9552;-95252;-9552;-9552;-95252;-9572;-9552;-9552;-95252;-9572;-9552;-9552;-9552;-9552;-95252;-9552;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;-95252;
e.g.g.g.C9553;Hex│Hex│UNHEX≥9553;
95688852;9552;9552;9552;95252;9552;9552;9552;9552;9578;9578;957852;9552;9552;9552;9552;9552;95252;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;95252;9552;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;5252;95252;95252;95252;
e.9553616263│7B│Postgresql±955363;
95622;9552;9552;9552;9522;9552;9552;9552;9552;9575;9575;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;9552;95252;95252;9552;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;95252;5252;95252;95252;95252;