从连接(1到多个)postgresql接收1行

时间:2012-07-01 06:56:11

标签: sql postgresql one-to-many postgresql-9.1

我有这个问题:

     
  • 我有2张主要桌子(公寓,租户),有1对多(1间公寓,多个租户)。
  • 我正在试图把我所有的公寓都搬到他的租户那里。
  • 优先租户是ot = 2的人(有2个可能的值:1或2)。
我尝试使用子查询,但在postgresql中,它不允许您返回超过1列 我不知道如何解决它。这是我最新的代码:
SELECT a.apartment_id, a.apartment_num, a.floor, at.app_type_desc_he, tn.otype_desc_he, tn.e_name
FROM 
  public.apartments a INNER JOIN public.apartment_types at ON
  at.app_type_id = a.apartment_type INNER JOIN 
    (select t.apartment_id, t.building_id, ot.otype_id, ot.otype_desc_he, e.e_name
     from   public.tenants t INNER JOIN public.ownership_types ot ON
        ot.otype_id = t.ownership_type INNER JOIN entities e ON
        t.entity_id = e.entity_id
     ) tn ON
  a.apartment_id = tn.apartment_id AND tn.building_id = a.building_id
WHERE 
  a.building_id = 4 AND tn.building_id=4
ORDER BY
  a.apartment_num ASC, 
  tn.otype_id DESC

提前完成

1 个答案:

答案 0 :(得分:2)


SELECT a.apartment_id, a.apartment_num, a.floor
      ,at.app_type_desc_he, tn.otype_desc_he, tn.e_name
FROM   public.apartments a
JOIN   public.apartment_types at ON at.app_type_id = a.apartment_type
LEFT JOIN  (
    SELECT t.apartment_id, t.building_id, ot.otype_id
          ,ot.otype_desc_he, e.e_name
    FROM   public.tenants t
    JOIN   public.ownership_types ot ON ot.otype_id = t.ownership_type
    JOIN   entities e ON t.entity_id = e.entity_id
    ORDER  BY (ot.otype_id = 2) DESC
    LIMIT  1
    ) tn ON (tn.apartment_id, tn.building_id)=(a.apartment_id, a.building_id) 
WHERE  a.building_id = 4
AND    tn.building_id = 4
ORDER  BY a.apartment_num;  -- , tn.otype_id DESC -- pointless

重要部分强调。

无论哪种情况都适用。

  • 如果有公寓的租户,将返还1个。
  • 如果ot.otype_id = 2有一个(或多个)租户,则属于该类型。
  • 如果没有租户,公寓仍然归还。

如果,ot.otype_id ...

  

有两个可能的值:1或2

...你可以简化为:

ORDER  BY ot.otype_id DESC

调试查询

尝试从基本查询中删除WHERE子句并更改

JOIN   public.apartment_types

LEFT JOIN   public.apartment_types

并逐个添加它们以查看哪个条件排除了所有行。

at.app_type_ida.apartment_type真的匹配吗?