我希望从PostgreSql数据库获取有关所有关系的数据,如
这样的查询SELECT
[creatorUser].[primTableName].[primColumnName] AS primary_column,
[creatorUser].[foreignTableName].[foreignColumnName] AS foreign_column,
FROM
sys.sysidx si,
sysidxcol sic,
sys.SYSFKCOL sfc,
sysusers su,
sys.systable st,
sys.syscolumn sc
WHERE
si.table_id=sic.table_id AND
si.index_id=sic.index_id AND
sfc.primary_column_id=sic.primary_column_id AND
sfc.foreign_table_id=sic.table_id AND
st.table_id=sfc.foreign_table_id AND
su.uid=st.creator AND
sc.column_name=si.index_name
任何人都可以提供帮助,如何获取数据?如何成为正确的查询
owner1.table1.primCol1 owner1.table1.foreignCol1
owner1.table1.primCol2 owner1.table1.foreignCol2
..
答案 0 :(得分:2)
PostgreSQL没有sys
个表,所以不清楚你怎么可能期望该查询起作用。鉴于您的意见,我猜这是您在Sybase上使用的查询,并且您希望将其翻译为PostgreSQL。
好吧,假设Sybase语法:
[creatorUser].[primTableName].[primColumnName] AS primary_column,
[creatorUser].[foreignTableName].[foreignColumnName] AS foreign_column,
表示“连接创建关系的用户,表名和列名”我可能会在PostgreSQL中做一些事情,如:
SELECT
format('%I.%I.%I', fk.table_schema, fk.table_name, fk.column_name) AS foreign_side,
format('%I.%I.%I', pk.table_schema, pk.table_name, pk.column_name) AS target_side
FROM
information_schema.referential_constraints rc
INNER JOIN information_schema.key_column_usage fk
ON (rc.constraint_catalog = fk.constraint_catalog
AND rc.constraint_schema = fk.constraint_schema
AND rc.constraint_name = fk.constraint_name)
INNER JOIN information_schema.constraint_column_usage pk
ON (rc.unique_constraint_catalog = pk.constraint_catalog
AND rc.unique_constraint_schema = rc.constraint_schema
AND rc.unique_constraint_name = pk.constraint_name);
除了format(...)
也适用于Sybase之外,运气不错。
输出如:
foreign_side | target_side
---------------------+---------------------------------
public.users.id_cat | public.usercategories.id_numcat
(1 row)
那是schema.table.column。我猜测Sybase的“creatorUser”在这种情况下确实是“架构”。
答案 1 :(得分:1)
您应该在pg_catalog或information_schema架构下查询相应的表。找出正确查询的最简单方法是运行(... =其他命令行选项,如用户,数据库......)
psql -E ...
然后psql显示内部命令中使用的元数据查询,如\ d,\ dt,\ dv,......来自手册:
-E
--echo-hidden
Echo the actual queries generated by \d and other backslash commands. You can use this to study psql's internal operations. This is equivalent to setting the variable ECHO_HIDDEN from within psql.
information_schema与pg_catalog相同,但更多的是portalbe(在SQL标准中定义)。如果您的应用仅使用postgres,那么我将使用pg_catalog而不是information_schema