1

I have an SQL query like this:

SELECT DISTINCT(id) FROM users WHERE ...

and I would like to display the results like that:

user=12355
user=78949
user=9898
user=489891

Basically with "user=" prepended. Is it possible to do this with PostgreSQL? I've tried with STRING_AGG('user=', DISTINCT(id)) but got an error on DISTINCT(id). Any idea?

4

4 回答 4

4

GROUP BY我会为此使用平原。

SELECT format('user=%s',id)
FROM users
GROUP BY id;

http://sqlfiddle.com/#!1/39727/3

这将比DISTINCT在字符串连接上使用更有效。

于 2013-06-26T05:05:58.323 回答
3

You should be able to use || for string concatenation:

SELECT DISTINCT('user=' || id) 
FROM users 
WHERE ...

This might be useful as well:

http://www.postgresql.org/docs/current/static/functions-string.html

于 2013-06-26T04:03:17.187 回答
3

您收到错误消息的唯一原因string_agg()是您忘记了所需的第二个参数。这个非常简单的查询就可以了:

SELECT string_agg('user=' || id, E'\n')
FROM   users 
WHERE  ...

E'\n'.. 换行符

生成一行,其中的字符串与您的问题中的字符串完全相同。
您不需要DISTINCT或者GROUP BY除非您有重复项id- 在这种情况下您需要一个子查询:

SELECT string_agg('user=' || id, E'\n')
FROM  (SELECT id FROM users GROUP BY id) x
于 2013-06-27T00:41:24.033 回答
1

只需从用户中选择 concat('user=',id)

于 2015-03-15T12:12:19.613 回答