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
这里的解释。)
还有更多相关答案。使用搜索。
顺便说一句,LIKE
在student_name LIKE 'John Doe'
没有意义。如果没有通配符,请使用=
。