显示列的 sql 查询输出

Posted

技术标签:

【中文标题】显示列的 sql 查询输出【英文标题】:display sql query output for columns 【发布时间】:2019-03-02 00:44:30 【问题描述】:

我有这张桌子

id | apple | banana | coconut | pear|
1     1       1       1           0
2     0       0        1          1
3     1       0        0          1

还有这个sql查询

select tree
from ((select id, 'apple' as tree
       from trees
       where apple = 1
      ) union all
      (select id, 'banana' as tree
       from trees
       where banana = 1
      ) union all
      (select id, 'coconut' as tree
       from trees
       where coconut = 1
      ) union all
      (select id, 'pear' as tree
       from trees
       where pear = 1
      )
     ) t
where id = 1;

输出是

apple 
banana
coconut

我将如何在 php 中写这个,以便我可以回显结果

这是我目前所拥有的

$sql = " select tree
    from ((select id, 'apple' as tree
           from trees
           where apple = 1
          ) union all
          (select id, 'banana' as tree
           from trees
           where banana = 1
          ) union all
          (select id, 'coconut' as tree
           from trees
           where coconut = 1
          ) union all
          (select id, 'pear' as tree
           from trees
           where pear = 1
          )
         ) t
    where id = '$id'";
 $result = mysqli_query($conn, $sql);

但我不知道在此之后该怎么做,我不能放一个 while 循环或只是回显它给出错误的结果

【问题讨论】:

【参考方案1】:

您可以使用mysqli_fetch_assoc() 简单地循环您的结果:

while ($row = mysqli_fetch_assoc($result)) 
    echo $row['tree'] . "\n";

但是,这样做可能更简单/更有效,它使用列名生成输出数据,当列中的值不为 0 时回显名称:

$sql = "SELECT * FROM trees WHERE id = '$id'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) 
    foreach ($row as $key => $value) 
        if ($key == 'id') continue;
        if ($value) echo "$key\n";
    

【讨论】:

以上是关于显示列的 sql 查询输出的主要内容,如果未能解决你的问题,请参考以下文章

SQL 怎样将查询出某列的多行数据,变为一行显示? 通过SQL语句查询出结果 AutoID cT

SQL:根据 B 列中的布尔值更改 SELECT 查询以在 A 列上显示不同的值

如何在 SQL 的查询中创建一列的 SUM?

SQL*Plus 格式化查询结果

SQL查询显示员工表中ename列的长度和前3个字符[重复]

SQL查询显示emp表中ename列的长度和前3个字符