獲得mysql、postgresql元數據信息


獲得mysql、postgresql元數據信息

源於最近新的需求需要一個新功能,需要獲得元數據表的信息,包括comment等,展示在頁面上。

mysql

-- 查詢當前庫有多少個表
select 
	count(*) 
from information_schema.tables 
where 
	table_schema = (select database())
	
-- 查詢所有的表及其元數據信息
select 
	table_name tableName, 
	engine, 
	table_comment tableComment, 
	create_time createTime 
	from information_schema.tables 
where 
	table_schema = (select database()) 
	
-- 獲得表的所有列的元數據信息
select 
	column_name columnName, 
	data_type dataType, 
	column_comment columnComment, 
	column_key columnKey, extra 
from information_schema.columns
where 
	table_name = 'emp' 
	and table_schema = (select database()) 
order by ordinal_position


-- 獲得表的引擎和注釋
select 
	table_name tableName, 
	engine, 
	table_comment tableComment, 
	create_time createTime 
from information_schema.tables 
where 
	table_schema = (select database()) 
	and table_name = 'emp' 

postgresql

postgresql比較特殊一點,因為postgresql使用了namespace的概念,可能同一個庫中不同的namesespace有兩個表明一樣的表:

-- 查詢某個命名空間的所有的表名
select tablename from pg_tables where schemaname = 'public'

-- 查詢某個命名空間所有的表的注釋信息
select 
 relname as "name",
 obj_description(oid) as "comment"
from pg_class 
where 
  obj_description(relnamespace) like '%public%'
-- 	and relname = 't_yl_hjdm' -- 需要指定某個表的時候給表名的條件

-- 查詢某個命名空間的某個表的所有列的元數據信息
-- 兩個函數的用法參考官方文檔:https://www.postgresql.org/docs/10/functions-info.html
-- 關於存儲表和列元數據的信息文檔:https://www.postgresql.org/docs/10/catalogs.html
select 
	col_description(pa.attrelid, pa.attnum) as "comment",
	format_type(pa.atttypid, pa.atttypmod) as "type",
	pa.attname as "name"
from pg_class as pc, pg_attribute as pa, pg_namespace as pn
where 
	pa.attrelid = pc.oid
	and pn.nspname = 'public'
	and pc.relname = 't_yl_hjdm'
	and col_description(pa.attrelid, pa.attnum) is not null

參考:
postgresql文檔:https://www.postgresql.org/docs/10/index.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM