根据您的查询,如果我们需要考虑优化,我们将考虑一些情况
案例 1:
正如您所提到的,您将拥有 60(链接)* 5(类别),这些从 mysql 端本身很容易处理。我们可以很好地使用我们的 SQL 技术本身并从中获得优势。
您总是可以混合使用 php 处理 + SQL。PHP的处理速度比mysql快。所以,抓住它。
Your query can also be solved by SQl alone and the query mentioned by paolo can be used simply.
case 2:
There are situation where either or both one of the table participating tables have too high number of records. when there is a join between them it results into high number of combinations i.e join size
eg: links(100000) * categories(10) = 1 million
In these cases, u can try to avoid joins.
You can take advantage of indexes.
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows.
There are techniques like flat files i.e schema free databases like MongoDB which dont use concept of joins but if you plan on it running it on a huge site (huge, meaning that you need many many servers to host it)
MySQl scales well and you have to think something out of it when you are in a huuuuuuuge environment.
Here,I have solved your query without using joins and any dependent query. I have just fetch results and just used array mapping techniques only which is faster.
$query = mysql_query("SELECT * FROM category order by `order` asc");
while($row = mysql_fetch_assoc($query) ) {
$categories[$row['id']]['cat'] = $row['cat'];
$categories[$row['id']]['order'] = $row['order'];
}
$query = mysql_query("SELECT * FROM links ORDER BY `order` ASC ");
$count =0;
while($row = mysql_fetch_assoc($query) ) {
$links[$row['cat-id']][$count]['link'] = $row['link'];
$links[$row['cat-id']][$count]['order'] = $row['order'];
$links[$row['cat-id']][$count]['cat-id'] = $row['cat-id'];
$count++;
}
foreach ($categories as $id=$value) {
foreach ($links[$id] as $link_info) {
if ($last_cat != $link_info['cat-id'])
print '<h3' . $categories[$link_info['cat-id']]['cat'] . '</h3';
print $link_info['link'] . '<br';
$last_cat = $link_info['cat-id'];
} }