使用SQL根据名称选择表中的列子集

时间:2017-12-21 18:18:55

标签: sql postgresql nested-select

我在Postgres DB中有一个表,其中有很多列,例如“id,name,a01,a02,a03,...,a20,b,c,d,e,f”。我想检查这些'aXX'列中是否有任何值为'Y'。 我知道琐碎的方式:

SELECT name FROM table T 
WHERE T.a01 = Y OR T.a02 = Y OR ... OR T.a20 = Y

我想知道是否有任何方法可以使用基于这些列名的循环或嵌套选择查询,因为它们有一个模式,而不是在WHERE中单独对它们进行硬编码?

提前致谢。

2 个答案:

答案 0 :(得分:1)

  

SQL中不可能,但......

你可以在PostgreSQL

中完成

如果您只想要id,字段名称(键)和您可以写的值:

select d.id, e.key, e.value
  from the_data d, jsonb_each_text(to_jsonb(d.*)) e
  where value::integer = -1;

如果你想要你可以的行:

select * 
  from the_data
  where id in (
    select d.id
      from the_data d, jsonb_each_text(to_jsonb(d.*))
      where value::integer = -1
  );

请参阅:http://rextester.com/CRGXPS45970

中的运行示例

EDITED

您可以过滤字段或所需内容。例如:

select d.id, e.key, e.value
  from the_data d, jsonb_each_text(to_jsonb(d.*)) e
  where value::integer = -1 and key like 'a%';

select * 
  from the_data
  where id in (
    select d.id
      from the_data d, jsonb_each_text(to_jsonb(d.*))
      where value::integer = -1 and key like 'a%'
  );

您可以在此处查看:http://rextester.com/EESKX21438

答案 1 :(得分:0)

没有办法完全按照自己的意愿去做。您可以先执行另一个查询来获取所有列名,然后在PHP中处理结果,但我认为这比仅编写列更复杂。名字倒了。