【问题标题】:SQL to show all entries within a number of categoriesSQL 显示多个类别中的所有条目
【发布时间】:2009-09-28 11:06:02
【问题描述】:

我正在三个表上编写一个 sql 查询,用于查找和显示类别以及每个类别中的所有条目

例如

第 1 类 帖子 1 帖子 2 帖子 3 发布 4

第 2 类 发布 5 发布 6

第 3 类 发布 7 发布 8

我显示了类别,但只能从每个类别中获取一项。任何人都可以提出更好的方法吗?

$sql = "SELECT c.CategoryDescription, f.Description, l.FileID, l.CategoryID FROM 
FileCategories c, Files f, FilesLK l WHERE
c.PictureCategoryID IN (58, 59, 60, 61, 62, 63) AND 
c.PictureCategoryID = l.CategoryID AND
f.ID = l.FileID
GROUP BY c.CategoryDescription";

while($row = mysql_fetch_array($result)) {
  $html .= '<h3><a href="#">'.$row['CategoryDescription'].'</a></h3>
  <div>'.$row['Description'].'</div>';
}

谢谢

【问题讨论】:

  • 请发布表定义以明确表之间的关系。

标签: php sql join group-by


【解决方案1】:

您的 GROUP BY c.CategoryDe​​scription 确保每个类别只有一个帖子。不能真正减少这样的行。为什么不在循环中加入一些逻辑以使其更智能。

$thiscat = '';
while($row = mysql_fetch_array($result)) {
  if($thiscat != $row['CategoryDescription']) {
    $thiscat = $row['CategoryDescription'];
    $html .= '<h3><a href="#">'.$thiscat.'</a></h3>';
  }
  $html .= '<div>'.$row['Description'].'</div>';
}

如果您从 SQL 中删除 group by 并将循环更改为此,它将仅在类别描述更改时打印标题行。

我个人建议这样写:

$thiscat = '';
while(list($cat,$desc,$fileid,$catid) = mysql_fetch_row($result)) {
  if($thiscat != $cat) {
    $thiscat = $cat;
    $html .= "<h3><a href=\"#\">$thiscat</a></h3>";
  }
  $html .= "<div>$desc</div>";
}

只需要对标签属性使用转义的双引号或单引号就可以了,但更简洁,更容易阅读/排除故障......恕我直言。

HTH :)

【讨论】:

    【解决方案2】:

    对不起,这是基本布局,省略了一些不相关的字段:

    FileCategories
    ID | CategoryDescription
    
    
    Files
    ID | Description
    
    FilesLK
    FileID | CategoryID
    

    【讨论】:

    • 请编辑问题,然后删除此“答案”。 Stackoverflow 不像一个“普通”的论坛。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 2013-02-28
    • 2014-11-18
    • 1970-01-01
    相关资源
    最近更新 更多