我有2张桌子: 第一个名为“类别”的表包括:category_id,category_name等。 第二个名为“collections”的表包括:collection_id,collection_name,short_description,category_id等。
我想在网格视图中列出它们:
category_name no.1
collection_name no.1 (belong to category_name no.1)
collection_name no.2 (belong to category_name no.1)
collection_name no.3 (belong to category_name no.1)
category_name no.2
collection_name no.1 (belong to category_name no.2)
collection_name no.2 (belong to category_name no.2)
collection_name no.3 (belong to category_name no.2)
category_name no.3
collection_name no.1 (belong to category_name no.3)
collection_name no.2 (belong to category_name no.3)
collection_name no.3 (belong to category_name no.3)
等
这些项目遵循字母顺序,如果没有集合,则不显示这些类别。
我尝试使用select distinct和inner join选择它们:
$sql="SELECT DISTINCT collections.category_id, collections.collection_name, categories.category_id, categories.category_name
FROM collections
INNER JOIN categories
ON collections.category_id=categories.category_id
ORDER BY categories.category_id, collections.collection_name";
$result = $mysqli->query($sql);
$row_category_id="";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (!$row_category_id==$row["category_id"]) {
echo "category: " . $row["category_name"]."<br>"."collection: " . $row["collection_name"]."<br>";
$row_category_id=$row["category_id"];
} else {
echo "collection: " . $row["collection_name"]."<br>";
$row_category_id=$row["category_id"];
}
}
} else {
echo "no result";
}
$row_category_id="";
目前的结果是:
category_name no.1
collection_name no.1 (belong to category_name no.1)
collection_name no.2 (belong to category_name no.1)
collection_name no.3 (belong to category_name no.1)
collection_name no.1 (belong to category_name no.2)
collection_name no.2 (belong to category_name no.2)
collection_name no.3 (belong to category_name no.2)
collection_name no.1 (belong to category_name no.3)
collection_name no.2 (belong to category_name no.3)
collection_name no.3 (belong to category_name no.3)
有人可以帮我吗?非常感谢。