sql - 子查询中的动态表名和变量
问题描述
我正在尝试构建如下查询:
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
然后comment
andlike
表可能如下所示:
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 中提到),archived
comment table 中的列存在并且archived = 0
解决方案
推荐阅读
- python - matplotlib 本地化的不同结果取决于解释器
- python - 如何使用 Python 将数组循环到 csv 中?
- seq - 关于“最大范围”的面试问题毫无意义
- sql - 条件表达式 MS Access 中的 SQL 数据类型不匹配
- php - Illuminate\Database\QueryException:SQLSTATE[HY000]:一般错误:1364 字段 'id' 没有默认值
- java - 通过 Java 中 ActiveDirecotry 中的 LDAP 解析其 GUID 来获取对象的名称
- c++ - 不同翻译单元中模板/内联函数的地址
- django - 从一个页面重定向到另一个页面时出现问题
- javascript - div 及其内容未显示在页面中
- c++ - WebRTC 从不流式传输视频