选择第一个NOT NULL列,然后获取该列的名称


Selecting first NOT NULL column, then getting name of that column

我用以下方式设置了一个数据库表:

table
--------
id: 123
name: test
description: lorem ipsum
a: NULL
b: NULL
c: NULL
d: lorem ipsum
e: NULL
f: lorem ipsum

然后我的PHP页面上有一个变量$id = 123

如何返回第一个NOT NULL列的名称,仅在a, b, c, d, e, f中搜索?因此,在这种情况下,查询会将df返回到字符串中。(NOTlorem ipsum

以下是我试图让你更好地了解我需要的东西:

(据我所知,COALESCE()将"返回第一个非NULL参数")

$cat = mysql_query("SELECT coalesce(a, b, c, d, e, f) FROM table WHERE `id`='$id' LIMIT 1");
$cat = mysql_fetch_assoc($cat);
$cat = array_shift(array_values($cat)); 

上面的查询几乎完成了我想要的,它返回第一个NOT NULL列的信息(所以在本例中,它返回lorem ipsum)。。。我需要的是该列的NAME

因此,我尝试了$cat = mysql_field_name($cat, 0);(请参阅下面的信息),但显然这需要在查询中运行,而不是从mysql_fetch_assoc返回的字符串。所以我试着这样做,并在查询上运行mysql_field_name,当我回显它时,它会返回原始查询(coalesce(a, b, c, d, e, f))的一部分。奇怪吧?

(info--mysql_field_name--获取结果中指定字段的名称)

概括一下:我提供的3行PHP正在工作,并提供来自列的信息,但我需要一种方法来获取该列的NAME并将其存储到字符串中。感谢


在遵循Gordon的方法后,我将上面示例中PHP的第一行(查询)更改为$cat = mysql_query("select (case when a is not null then 'a' when b is not null then 'b' when c is not null then 'c' when d is not null then 'd' when e is not null then 'e' when f is not null then 'f' end) FROM directory WHERE id='$id' LIMIT 1"),但它返回了一个布尔值(所以我不能运行mysql_fetch_assoc,因为它实际上没有返回任何内容),我检查了所有列的名称是否正确等。

最简单的解决方案是借助array_filter(array_filter)您可以给它一个数组,在没有回调的情况下,它会给您所有求值为true的元素。列名保留,以便您可以使用键函数
这样的东西:

$keys = key(array_filter($cat))

在$keys[0]上可以找到你的名字。

只需使用case:

select (
         case 
               when a is not null then 'a'
               when b is not null then 'b'
               when c is not null then 'c'
               when d is not null then 'd'
               when e is not null then 'e'
               when f is not null then 'f'
         end
      )