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

提前感谢

4

1 回答 1

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

Crucial part emphasized.

This works in either case.

  • If there are tenants for an apartment, exactly 1 will be returned.
  • If there is one (or more) tenant of ot.otype_id = 2, it will be one of that type.
  • If there are no tenants, the apartment is still returned.

If, for ot.otype_id ...

there are 2 possible values: 1 or 2

... you can simplify to:

ORDER  BY ot.otype_id DESC

Debug query

Try removing the WHERE clauses from the base query and change

JOIN   public.apartment_types

to

LEFT JOIN   public.apartment_types

and add them back one by one to see which condition excludes all rows.

Do at.app_type_id and a.apartment_type really match?

于 2012-07-01T13:43:28.037 回答