查询有问题。我的wscategories存储在线商店的主要类别,而我的wssubcategories表存储表的子类别和名为“parentcategory”的外键。我正在尝试列出主要类别,子类别位于la:
下面上装
T恤
织造布
毛衣
裤子
短裤
牛仔裤
我写的查询/结果如下:
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND
b.parentcategory = a.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['maincategory'];
echo "<br/>";
echo $row['smallcategory'];
echo "<br/>";
}
返回:
上衣
T恤
上衣
毛衣
上衣
织造布
等。我希望脚本只显示一次主类别,然后显示下面的子类别与多次显示它。有帮助吗?
答案 0 :(得分:1)
尝试这样的事情
// note we need to order by maincategory for this to work
//
$query = "SELECT DISTINCT a.categoryname AS maincategory, b.categoryname AS
smallcategory FROM wscategories a, wssubcategories b WHERE a.SECTION = 'girls' AND
b.parentcategory = a.id
ORDER BY maincategory ASC,
smallcategory ASC
";
$result = mysql_query($query) or die(mysql_error());
// keep track of previous maincategory
$previous_maincategory = NULL;
while ($row = mysql_fetch_assoc($result))
{
// if maincategory has changed from previouscategory then display it
if ($previous_maincategory != $row['maincategory']) {
echo $row['maincategory'];
}
echo "<br/>";
echo $row['smallcategory'];
echo "<br/>";
// record what the previous category was
$previous_maincategory = $row['maincategory'];
}
答案 1 :(得分:0)
在回显主类别后设置一个标志,如下所示:
$echoed_main = false;
while ($row = mysql_fetch_array($result)) {
if (!$echoed_main) {
echo $row['maincategory'];
echo "<br/>";
$echoed_main = true;
}
echo $row['smallcategory'];
echo "<br/>";
}