如何从多列中选择不同的列

发布于 2024-09-26 18:53:03 字数 804 浏览 4 评论 0原文

你好 我确信有人对这种操作有疑问,但我似乎无法理解它。
我有一个像这样的表:


product_id | saved_by | deleted_by | accepted_by | published_by
-----------+----------+------------+-------------+-------------
 1         | user1    |            | user1       |
-----------+----------+------------+-------------+-------------
 2         |          | user2      |             |
-----------+----------+------------+-------------+-------------
 3         | user2    |            |             | user3
-----------+----------+------------+-------------+-------------
 4         |          |            | user1       | user4
-----------+----------+------------+-------------+-------------

我正在尝试创建一个查询,该查询将选择这些字段中的所有用户,从而明显地产生如下结果:


users
------
user1
user2
user3
user4

有指针吗?

Hi
I'm sure there's query for this kind of operation, but I just can't seem to get it.
I have a table like this:


product_id | saved_by | deleted_by | accepted_by | published_by
-----------+----------+------------+-------------+-------------
 1         | user1    |            | user1       |
-----------+----------+------------+-------------+-------------
 2         |          | user2      |             |
-----------+----------+------------+-------------+-------------
 3         | user2    |            |             | user3
-----------+----------+------------+-------------+-------------
 4         |          |            | user1       | user4
-----------+----------+------------+-------------+-------------

And I'm trying to create a query that would select all the users in those fields distinctly resulting in something like this:


users
------
user1
user2
user3
user4

Any pointers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2024-10-03 18:53:03

首先想到的是对列进行 UNION:

  SELECT t.users
  FROM
  (
  SELECT saved_by AS users
  FROM table
  UNION 
  SELECT deleted_by
  FROM table
  UNION 
  SELECT accepted_by
  FROM table
  UNION 
  SELECT published_by
  FROM table
  ) AS t;

http://postgresql.org /docs/9.0/interactive/sql-select.html

作为旁注,如果此数据已标准化,那么按照您想要的方式获取数据会容易得多。

First thing that comes to mind is to UNION the columns:

  SELECT t.users
  FROM
  (
  SELECT saved_by AS users
  FROM table
  UNION 
  SELECT deleted_by
  FROM table
  UNION 
  SELECT accepted_by
  FROM table
  UNION 
  SELECT published_by
  FROM table
  ) AS t;

http://postgresql.org/docs/9.0/interactive/sql-select.html

As a side note if this data was normalized it would be much easier to get the data the way you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文