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

标签 php mysql sql phpmyadmin

我的 SQL 语句看起来像

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

我得到了这个结果

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

我想要的是让 AS 为每个功能指定一个唯一的名称,例如 feature1 feature2 feature3 这样这 4 行就可以显示在一行中。这可能吗?

我正在寻找的输出看起来像

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

最佳答案

您请求的确切输出不容易实现,除非使用 GROUP_CONCAT() 将功能列为逗号分隔列表而不是单独的列。

因为没有一组固定的可能的功能适用于您的所有产品,所以您将无法使用数据透视查询。

我建议使用 GROUP_CONCAT() 以逗号分隔列表的形式检索特征,然后在您的应用层中使用 PHP 将它们分开。

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

输出结果如下:

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

在您的 PHP 中,当获取结果时,explode() 将特征放入一个数组中:

$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']);
}

最后,访问应用程序中的功能:

foreach ($resultset as $r) {
  echo $r['features'][0];
  echo $r['features'][1];
  echo $r['features'][2];
  echo $r['features'][3];
}

关于php - 对于 SQL 查询返回的每个结果,我想给出一个不同的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868545/

相关文章:

php - 带有整数值的html下拉列表?

javascript - 如何为聊天室显示从数据库接收的一系列消息

mysql - 为 SQL 分配别名

python - mysql检索数据出错

sql - 获取mysql数据表中用户卡的最早时间戳

php - 为什么从我的 Vagrant 邮箱用 PHP 发送邮件这么慢?

php - 时区和夏令时问题

php - 如何在nginx服务器中创建虚拟主机?和 ajax 调用

php - 从 mysql_query 切换到 PDO 的问题

mysql - 对包含零的列进行条件 ORDER BY