假设我有一个这样的数据库设计:
对于数据:
id | title | category
1 | first title | 1
2 | second title | 4
3 | third title | 5
4 | fourth title | 2
5 | fifth title | 3
6 | other title | 1
对于类别:
id | name
1 | music
2 | movies
3 | funny
4 | people
5 | sport
如何输出每个类别的列表,其中包含该类别中的项目标题?
有人认为:
<div>
<h1>music</h1>
<div>first title</div>
<div>other title</div>
<div>
<div>
<h1>movies</h1>
<div>fourth title</div>
<div>
// and so on...
我不知道如何为这样的结果制定 mysql 查询......
有人可以告诉我吗?(我希望这个例子很容易理解)
提前谢谢。
编辑:我使用了Eugen Rieck的代码,但我不知道如何做以下事情
我如何按categories.id
订购,titles.id
同时最终使用WHERE条件?
像这样的东西:ORDER BY titles.id DESC LIMIT 0, 10 WHERE titles.views > 10
假设你的第一个表被称为titles
,第二个表categories
,使用类似
SELECT categories.name as cat, tiltes.title as title
FROM categories INNER JOIN titles ON titles.category=categories.id
ORDER BY categories.id
然后执行组更改循环
define('MAX_TITLES_PER_CAT',10);
$cat='';
$tcount=0;
while (true) {
//Fetch a row depending on your DB framework, eg. mysql_fetch_row()
if ($row['cat']!=$cat) {
if ($cat!='') echo '</div>';
$cat=$row['cat'];
$tcount=MAX_TITLES_PER_CAT;
echo "<div><h1>$cat</h1>";
}
if ($tcount--<=0) continue;
echo '<div>'.$row['title'].'</div>';
}
if ($cat!='') echo '</div>';
编辑
我更新了上面的代码,将每个类别显示的标题数量限制为 MAX_TITLES_PER_CAT
- 请理解,如果每个类别的平均标题数量远高于 MAX_TITLES_PER_CAT
,这是非常低效的。
SELECT
t.title,
c.name
FROM
titles t
INNER JOIN categories c
ON c.id = t.category
ORDER BY
c.name
ASC
这为您提供了按类别排序的所有标题的列表。你在 PHP 中所做的大致如下:
$prevCategory = null;
while(fetchRows)
{
$newCategory = $row['name'];
if($prevCategory != $newCategory)
{
echo '<ul>{category name}</ul>';
}
echo '<li>{title}</li>';
$prevCategory = {category name};
}
请注意,这是半伪代码。它不会关闭以前的 UL,也不会根据您寻求的 HTML 格式。不过,这应该会让你继续前进。