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

问题描述 投票:0回答:2

我在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中单独对它们进行硬编码?

提前致谢。

sql postgresql nested-select
2个回答
1
投票

不可能在SQL但...

You can do it in 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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.