简体   繁体   English

如何使用SQL从数据库中获取键值对

[英]How to get a key value pair from a Database using SQL

I'm a new to SQL so, can you please help me in figuring out how to get a key-value pair from a SQL for example : Table A 我是SQL的新手,所以请您帮我弄清楚如何从SQL中获取键值对:表A

A(PK)    B(INT)  C       D
------ ------- ------- --------

1        X       Y        Z

2        A       B        C

I want the output in the form 我想要形式的输出

A = 1
B = X 
C = Y 
D = Z

i tried 我试过了

SELECT A,B,C,D from tableA ; 

But it only prints in the form 1 XYZ So, can you please help me ? 但是它仅以1 XYZ的形式打印,所以,请您能帮帮我吗?

Generally getting the column names along with the row values and formatting the result is a thing the SQL client provides for you. 通常,获取列名以及行值并格式化结果是SQL客户端为您提供的功能。 pgAdmin isn't really suited for this, a programming language would be better. pgAdmin并非真的适合于此,使用编程语言会更好。

For example, here's how you'd do it using Ruby and the ruby-pg gem . 例如,这是使用Ruby和ruby-pg gem的方法

#!/usr/bin/env ruby

require 'pg'

conn = PG.connect( dbname: 'test' )
conn.exec( "SELECT * FROM tableA" ) do |result|
  result.each do |row|
    row.each do |column,value|
      puts "#{column} = #{value}"
    end
  end
end

You can do a union of the queries picking one column at a time 您可以对查询进行联合,一次只选择一列

SELECT 'A', A from tableA WHERE ID = @ID
UNION
SELECT 'B', B from tableA WHERE ID = @ID
UNION
SELECT 'C', C from tableA WHERE ID = @ID
UNION
SELECT 'D', D from tableA WHERE ID = @ID

you will probably need to cast all the columns to a common type (varchar) for this to work. 您可能需要将所有列都转换为通用类型(varchar)才能起作用。

Another option is to create a function that returns the result as desired: 另一个选择是创建一个函数,该函数可根据需要返回结果:

create type crosstab_type as (row_num bigint, column_name text, value text);

create or replace function kv()
  returns setof crosstab_type
as
$$
declare 
  l_rec record;
  l_row bigint := 1;
begin
  for l_rec in select * from ani 
  loop
    return next (l_row, 'a', l_rec.a::text)::crosstab_type;
    return next (l_row, 'b', l_rec.b::text)::crosstab_type;
    return next (l_row, 'c', l_rec.c::text)::crosstab_type;
    return next (l_row, 'd', l_rec.d::text)::crosstab_type;
    l_row := l_row + 1;
  end loop;
end;
$$
language plpgsql;



select *
from kv();

returns: 返回:

row_num | column_name | value
--------+-------------+------
      1 | a           | 1    
      1 | b           | X    
      1 | c           | Y    
      1 | d           | Z    
      2 | a           | 2    
      2 | b           | A    
      2 | c           | B    
      2 | d           | C   

Online example: http://rextester.com/RCKB51862 在线示例: http : //rextester.com/RCKB51862

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM