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

Selecting subset of columns in table based on their names using SQL

我在 Postgres 数据库中有一个 table,它有很多列,例如 "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

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

提前致谢。

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

Imposible in SQL but...

你可以在 PostgreSQL 中做到这一点

如果只想要id,字段名(key)和value可以这样写:

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

已编辑

您可以过滤字段或您想要的内容。例如:

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