您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

搜索多个表,并在结果行中显示表名

搜索多个表,并在结果行中显示表名

您正在寻找动态sql。从系统目录中自动组装您的查询

SELECT string_agg('SELECT student_name, '''
                   || c.oid::regclass || ''' AS tbl, pid FROM '
                   || c.oid::regclass
                   || $$ WHERE student_name = 'John Doe'$$
                 , E'\nUNION ALL\n')
FROM   pg_namespace n
JOIN   pg_class     c ON c.relnamespace = n.oid
WHERE  n.nspname = 'public'         -- schema name where your tables lie
AND    c.relname LIKE 't%'          -- and / or filter table names
AND    EXISTS (
   SELECT 1 FROM pg_attribute 
   WHERE  attrelid = c.oid
   AND    attname = 'student_name'  -- make sure column exists
   AND    NOT attisdropped          -- and is alive
   );

产生查询字符串:

SELECT student_name, 'tbl1' AS tbl, pid FROM tbl1 WHERE student_name = 'John Doe'
UNION ALL
SELECT student_name, 'tbl2' AS tbl, pid FROM tbl2 WHERE student_name = 'John Doe'
UNION ALL
SELECT student_name, 'tbl3' AS tbl, pid FROM tbl3 WHERE student_name = 'John Doe'
...

然后在第二个调用中运行它,或者使用来使用PL / pgsql函数完全自动化它EXECUTE。示例:从表中选择一组动态列,并获取每个列的总和

查询生成@L_419_2@ 安全 代码,以防止SQL注入。oid::regclass这里的解释。)

还有更多相关答案。使用搜索。

顺便说一句,LIKEstudent_name LIKE 'John Doe'没有意义。如果没有通配符,请使用=

其他 2022/1/1 18:38:14 有406人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶