[英]Select current table name from postgresql
我有一個由多個子查詢組成的查詢,這些子查詢由UNION ALL
組合而成。
SELECT pan_hash, amount FROM humo_txns
UNION ALL
SELECT pan_hash, amount FROM uzcard_txns
LIMIT 10;
但是在檢索數據之后,我需要以某種方式找出數據的來源,所以我認為最好將表名(數據的來源)作為一個新列包含在內。
那么有什么辦法可以完成這樣的事情嗎?
SELECT <table_name>, pan_hash, amount FROM humo_txns
UNION ALL
SELECT <table_name>, pan_hash, amount FROM uzcard_txns
LIMIT 10;
您可以嘗試以下 -
SELECT 'humo_txns', pan_hash, amount FROM humo_txns
UNION ALL
SELECT 'uzcard_txns', pan_hash, amount FROM uzcard_txns
LIMIT 10;
沒有內置的 function 可以執行此操作,您必須在每個 select 中手動輸入名稱
SELECT CAST('humo_txns' AS VARCHAR(64)) AS table_name, pan_hash, amount FROM humo_txns
UNION ALL
SELECT CAST('uzcard_txns' AS VARCHAR(64)) AS table_name, pan_hash, amount FROM uzcard_txns
我建議至少在第一個查詢中轉換為一個 varchar 字段,該字段的長度足以容納任何表名。
是的,只需 select 文本文字並為此使用一些列別名:
SELECT 'humo_txns' AS table_name, pan_hash, amount FROM humo_txns
UNION ALL
SELECT 'uzcard_txns' AS table_name, pan_hash, amount FROM uzcard_txns
LIMIT 10;
(這為您提供了從表中所有行中任意選擇的十行,就像在您的查詢中一樣。因此您可以從兩個表中獲取行或僅從一個表中獲取行。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.