首页 > 解决方案 > PostgreSQL 使用来自 2 个表的数据,没有一个共同的值,而是一个布尔值

问题描述

我是 Postgres 的新手,正在尝试找到一种方法,如果一个表中的一个值读取为真,那么在另一个表中给我另一个值。

这是一张表:

itemid | pictureid1 | pictureid2 | smallpic | medpic | largepic 
--------+------------+------------+----------+--------+----------
    100 | 1          | 2          | t        | t      | t
    101 | 3          | 4          | t        | t      | t
    102 | 5          | 6          | t        | t      | t
    103 | 7          | 8          | t        | t      | t
    104 | 9          | 10         | t        | t      | t
    105 | 11         | 12         | t        | t      | t
    106 | 13         | 14         | t        | t      | t
    107 | 15         | 16         | t        | t      | t
    108 | 17         | 18         | t        | t      | t
    109 | 19         | 20         | t        | t      | t

这是另一个:

id |  size  |                size_url                 
----+--------+-----------------------------------------
  1 | small  | https://loremflickr.com/54/54?lock=
  2 | medium | https://loremflickr.com/400/400?lock=
  3 | large  | https://loremflickr.com/1000/1000?lock=

我试图得到它,如果对于一个特定的 itemid 它对 smallpic 说“真”,那么它在另一个表中给我 size_url 为 small,在第一个表中带有 pictureid1 和 pictureid2。

标签: sqlpostgresql

解决方案


如果我理解你(因为缺少预期的结果,

我曾经cte收集一次 url 信息,然后通过检查表中的值在子句item中使用它。select

with urls
as
(select max(case when id = 1 then url end) surl
       ,max(case when id = 2 then url end) murl
       ,max(case when id = 3 then url end) lurl
   from pic_urls
)
select i.itemid
      ,i.pictureid1
      ,i.pictureid2
      ,case when smallpic 
         then (select surl from urls)
       end small_url
     , case when medpic 
         then (select murl from urls)
       end med_url
     , case when largepic 
         then (select lurl from urls)
       end large_url
  from items i;

推荐阅读