【发布时间】:2017-06-30 12:59:14
【问题描述】:
我有 4 张桌子。 table1 有一列称为reportable_type,另一列称为reportable_id。可报告类型有两个值,table2 或 table3。 table2 和 table3 都有一个 table4_id 列。我正在尝试编写一个查询,让我在一个结果中获得 table1.id 和 table4.description。感觉就像一个关于 postgres 的案例陈述会让我到达那里,但我迷路了,还有两个案例陈述可能打破了这一点:
select t1.id, t4.description
from table1 as t1
case
when t1.reportable_type = ’table2’
then left join table2 as t2 on t1.reportable_id = t2.id
else left join table3 as t3 on t1.reportable_id = t3.id
end
left join table4 as t4 on
case
when t1.reportable_type = ’table2’
then t2.table4_id =t4.id
else t3.table4_id =t4.id
end
group by t4.description;
编辑:
想围绕这个添加一些数据,这样更清楚。
让我们使用以下数据:
table 1
IDs - 1, 2
reportable_type - table 2, table 3
reportable_id - 1, 1
table 2:
id - 1
t4_id - 1
table 3:
id - 1
t4_id - 2
table 4:
id - 1 ,2
description - first, second
所以查询的结果表应该是:
id - 1,2
description - first, second
【问题讨论】:
-
你不能随心所欲地改变语法规则。具体来说,
case在from子句中没有位置,我相信您知道。把它放在它确实有位置的地方——在select列表中。 -
除非 postgresql 有很大的不同,否则你不能在连接中使用这种方式。您可以在每次检查 table2 或不检查 table2 时创建一个“AND 语句;但是这种大小写的使用似乎很奇怪。
-
同意,我在这里遇到的问题是我不确定如何让这种关系发挥作用。完全同意上述语法不起作用,但认为它会让我更清楚地了解我想要做什么。
-
@xQbert 我不确定如何使用 and 语句来确定要加入哪个表的条件。你能扩展一下吗?
-
您可以左连接所有需要的表,然后有条件地在选择中显示您需要的表中的数据,但您不能有条件地连接,除非您进入更多程序化的 SQL。
标签: postgresql join case