dpjpo746884 2011-10-23 19:21
浏览 118
已采纳

对于SQL查询返回的每个结果,我想要给出一个不同的名称

My SQL statement looks like

SELECT beds.id,beds.name,beds.brand,beds.price,beds.disprice,feature.feature AS feature 
FROM beds,feature,bedFeatures 
WHERE bedFeatures.featureID = feature.id AND bedFeatures.bedID = beds.id

I get this result

id  name        brand   price   disprice    feature
10  Big Sleeper ZZZZ    10000   1           Oak
10  Big Sleeper ZZZZ    10000   1           Ash
10  Big Sleeper ZZZZ    10000   1           White

What I want is for the AS to give each feature a unique name such as feature1 feature2 feature3 so those 4 lines are displyaed in one. Is this possible?

The output I am looking for would look something like

id  name        brand   price   disprice    feature1 feature2 feature3
10  Big Sleeper zzzz    1000    1           Oak      Ash      White
  • 写回答

2条回答 默认 最新

  • duaabhuv188411 2011-10-23 19:47
    关注

    The exact output you request is not easily achieved, except by using GROUP_CONCAT() to list the features as a comma-separated list rather than individual columns.

    Because there is not a fixed set of possible features common to all your products, you will not be able to use a pivot query.

    I would recommend using GROUP_CONCAT() to retrieve the features as a comma-separated list, and then splitting them apart with PHP in your application layer.

    SELECT
      beds.id,
      beds.name,
      beds.brand,
      beds.price,
      beds.disprice,
      GROUP_CONCAT(feature) AS features
    FROM
      beds
      JOIN bedFeatures ON beds.id = bedFeatures.bedID
      JOIN features ON features.id = bedFeatures.featureID
    GROUP BY beds.id, beds.name, beds.brand, beds.price, disprice
    

    The output of this will look like:

    d  name        brand   price   disprice    features
    10  Big Sleeper zzzz    1000    1           Oak,Ash,White
    

    In your PHP, when fetching the results, explode() the features into an array:

    $resultset = array();
    while ($row = mysql_fetch_assoc($result)) {
      // First append the whole row onto the result set as it is...
      $resultset[$row['id']] = $row;
      // Overwrite the `features` string with an array instead...
      $resultset[$row['id']]['features'] = explode(",", $row['features']);
    }
    

    Finally, access the features in your application as:

    foreach ($resultset as $r) {
      echo $r['features'][0];
      echo $r['features'][1];
      echo $r['features'][2];
      echo $r['features'][3];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答