php - PHP 中加入的 MySQL 结果的排序输出

标签 php mysql join

在一个项目上通宵达旦,我的大脑一片空白……真的很简单的问题:

我有两个 MySQL 表,产品和类别。每个产品都属于一个类别。每个类别都有几种产品。

SELECT 
  p.uid as product_uid, p.name_NL as product_name, p.price as product_price,
  c.uid as category_uid, c.name_NL as category_name 
FROM 
  product p, category c
WHERE
  p.category_uid = c.uid

这让我对各自类别中的所有产品有了一个很好的概览。我的问题是关于在页面上输出这些数据。我的目标是:

<h1>Category name</h1>
<p>Product in this category</p>
<p>Other product in this category</p>

<h1>Next category</h1>
<p>Product in next category</p>

我脑子里一片空白。如何才能做到这一点?

我想避免进行子查询(如果可能的话)。

亲切的问候,

中号

最佳答案

如何添加 ORDER BY category_uid 以便产品在您的 SQL 查询中按类别排序。然后使用 PHP,遍历每个产品(行),当您遇到新类别时,添加一个新标题。

示例:

<?php

// ...

$previous_category_uid = null;

// Loop through each row.
while ( $row = $result->fetch_assoc() )
{
  // If the category UID is not the same as the one from the previous row, add a header.
  if ( $previous_category_uid != $row['category_uid'] )
  {
    echo '<h1>' . $row['category_name'] . '</h1>';
    $previous_category_uid = $row['category_uid'];
  }
}

此方法的好处是您不必嵌套查询。一个查询就足够了。

关于php - PHP 中加入的 MySQL 结果的排序输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541864/

相关文章:

javascript - Ajax 表单提交没有结果

php - mysql_close() : 5 is not a valid MySQL-Link resource in C:\wamp\www\Includes\footer. php 第 4 行

mysql - 只选择多次出现的一个条目

php - PHP 中的多个 SQL 查询组合会出现错误

php - 使两个查询互相作用

php - 与家族层次结构/布局相关的 MySQL 查询

php - 在推送到数据库之前使用 STR_TO_DATE()

php - MySQL 加入一张表。使用 where 子句列出值,然后在下方列出值

sql - 如何在没有过程的情况下使用一系列日期连接表

具有多种连接可能性的连接更新 MySQL