首页 > 解决方案 > 子查询中的动态表名和变量

问题描述

我正在尝试构建如下查询:

SELECT * FROM code
WHERE code.id = 2 AND
EXISTS (SELECT id FROM code.src_table_name WHERE (id = code.src_table_id AND (!archived OR archived = 0)))

显然这不起作用,但我将解释我想要实现的目标。

示例code表如下所示:

id  |  src_table_name  |  src_table_id
1      comment            2
2      like               21
3      comment            3

然后commentandlike表可能如下所示:

comment table
-------------
id  |  archived  |  comment
2      0            test
3      1            test1

like table
-------------
id
21

当然,这些是简化的表结构。

查询需要完成两个任务:

1. Check if table mentioned in src_table_name exists
2. Check if this table has a column called `archived`.
       - If `archived` column does not exist, continue
       - If `archived` column exists, make sure it is equal to 0

编辑:一些示例结果数据当我们有以下查询时:

SELECT * FROM code
WHERE code.id = 1 AND
EXISTS (SELECT id FROM code.src_table_name WHERE (id = code.src_table_id AND (!archived OR archived = 0)))

这会给我:

id  |  src_table_name  |  src_table_id
1      comment            2

因为comment表存在(在 src_table_name 中提到),具有 id 的行2存在(在 src_table_id 中提到),archivedcomment table 中的列存在并且archived = 0

标签: sqlpostgresql

解决方案


推荐阅读