[英]How to get the column name of a value in PostgreSQL?
Suppose we have 3 tables: 假设我们有3个表:
Table1: 表格1:
ID FrenchCity
1 Paris
2 Lille
3 Lyon
Table2: 表2:
ID IntlCity
1 Lille
2 Geneva
3 Toulouse
Table3: 表3:
ID BritishCity
1 London
2 Leeds
I would like to get the column name correspondent with a value. 我想获得与值对应的列名。 For instance, I give a value
Lille
and SQL should return Table1.FrenchCity Table2.IntlCity
. 例如,我给值
Lille
,SQL应该返回Table1.FrenchCity Table2.IntlCity
。 As I said, I would like to get the column name of a value. 如我所说,我想获取一个值的列名。 So
Lille
exists in 2 tables, I would like SQL to return the {{table name}}.{{column name}}
因此,
Lille
存在于2个表中,我希望SQL返回{{table name}}.{{column name}}
How to write a query to do that? 如何编写查询来做到这一点?
This work for you ? 这项工作适合您吗?
SELECT 'Table1.FrenchCity' as fieldName
FROM Table1
WHERE FrenchCity = 'Lille'
UNION ALL
SELECT 'Table2.IntlCity' as fieldName
FROM Table2
WHERE IntlCity = 'Lille'
UNION ALL
SELECT 'Table3.BritishCity' as fieldName
FROM Table3
WHERE BritishCity = 'Lille'
Then you can use array_agg
然后你可以使用
array_agg
SELECT array_agg(fieldName)
FROM (
previous union query
) t
you better create one table with 3 columns: 您最好创建一个包含3列的表格:
ID COUNTRY fieldName CITY
1 France FrenchCity Paris
2 France FrenchCity Lille
3 France FrenchCity Lyon
4 Intl IntlCity Lille
5 Intl IntlCity Geneva
6 Intl IntlCity Toulouse
ect. 等等。 then use query:
然后使用查询:
SELECT country || '.' || fieldName
FROM three_col_table
WHERE CITY = 'Lille'
If you don't wont to use DB metadata then you can to convert table data into the series of (column_name, column_value) pairs using row_to_json
and json_each_text
functions: 如果您不想使用数据库元数据,则可以使用
row_to_json
和json_each_text
函数将表数据转换为一系列(column_name,column_value)对:
with
-- Demo data start
Table1(ID, FrenchCity) as (values
(1, 'Paris'),
(2, 'Lille'),
(3, 'Lyon')),
Table2(ID, IntlCity) as (values
(1, 'Lille'),
(2, 'Geneva'),
(3, 'Toulouse')),
-- Demo data end
my_data as (
select 'Table1' as tbl, j.*
from Table1 as t, json_each_text(row_to_json(t.*)) as j(fld,val)
union all
select 'Table2' as tbl, j.*
from Table2 as t, json_each_text(row_to_json(t.*)) as j(fld,val)
-- ... and so on ...
)
select *, format('%s.%s', tbl, fld) as desirede_value from my_data
where val ilike 'lille';
tbl | fld | val | desirede_value
--------+------------+-------+-------------------
Table1 | frenchcity | Lille | Table1.frenchcity
Table2 | intlcity | Lille | Table2.intlcity
(2 rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.