gpt4 book ai didi

sql - 从加入的(1 到许多)postgresql 接收 1 行

转载 作者:行者123 更新时间:2023-11-29 13:06:07 26 4
gpt4 key购买 nike

我有这个问题:

  • 我有 2 个主表(公寓、租户),它们之间有一对多(1 间公寓、许 Multi-Tenancy )的连接。
  • 我正在尝试撤掉我所有的大楼公寓,但他的一位租户。
  • 优先租户是 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

提前致谢

最佳答案


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
<b>ORDER BY (ot.otype_id = 2) DESC</b>
<b>LIMIT 1</b>
) 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 ...

there are 2 possible values: 1 or 2

...你可以简化为:

ORDER  BY ot.otype_id DESC

调试查询

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

JOIN   public.apartment_types

LEFT JOIN   public.apartment_types

然后将它们一一添加回来,看看哪个条件排除了所有行。

at.app_type_ida.apartment_type 真的匹配吗?

关于sql - 从加入的(1 到许多)postgresql 接收 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11280151/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com