如何在PostgreSQL中获取值的列名?

时间:2016-06-17 15:09:29

标签: sql postgresql

假设我们有3个表:

表1:

/home/monju/full/app/bin/stopServer.sh

表2:

ID FrenchCity
1  Paris
2  Lille
3  Lyon

表3:

ID IntlCity
1  Lille
2  Geneva
3  Toulouse

我想让列名对应一个值。 例如,我给出一个值ID BritishCity 1 London 2 Leeds ,SQL应该返回Lille。 正如我所说,我想得到一个值的列名。所以Table1.FrenchCity Table2.IntlCity存在于2个表中,我希望SQL返回Lille

如何编写查询来执行此操作?

3 个答案:

答案 0 :(得分:2)

这项工作适合你?

 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'

然后您可以使用array_agg

SELECT array_agg(fieldName)
FROM (
       previous union query
     ) t

答案 1 :(得分:1)

您最好创建一个包含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

等。 然后使用查询:

SELECT country || '.' || fieldName  
FROM three_col_table
WHERE CITY = 'Lille'

答案 2 :(得分:0)

如果您不想使用数据库元数据,则可以使用row_to_jsonjson_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)