从多个表MySQL检索记录


Retrieving Records from Multiple Tables MySQL

我有两个表,第一个是材料,第二个是数据库中的类别。

材料表包含以下内容:

___________________________________________________________________________
|id |type|color|supplier|name   |image      |category_id|material_price_30|
|___|____|_____|________|_______|___________|___________|_________________|
|1  |Gran|Black|        |Angola |angola.jpg |3          |100              |
|2  |Gran|Blue |        |Emerald|emerald.jpg|0          |120              |
|3  |Marb|Black|        |Galaxy |galaxy.jpg |8          |135              |
|4  |Marb|White|        |Visag  |visag.jpg  |1          |115              |
|5  |Quar|White|Sill Co |Orissa |orissa.jpg |5          |106              |

类别表包含以下内容:

_____________________________
|id |name|thickness|price   |
|___|____|_________|________|
|1  |1   |30mm     |     169|
|2  |2   |30mm     |     244|
|3  |3   |30mm     |     280|
|4  |4   |30mm     |     316|
|5  |5   |30mm     |     347|
|6  |6   |30mm     |     411|
|7  |7   |30mm     |     496|
|8  |8   |30mm     |     544|
|9  |9   |30mm     |     612|
|10 |10  |30mm     |     689|
|11 |11  |30mm     |     775|

我一直在使用以下脚本从MATERIAL中检索所有图像,但现在也需要从CATEGORY中添加价格,只是不知道如何添加。MATERIALS中的category_ id应标识category表中类别的价格。

你们能帮我把它们连接起来吗?

这是我使用了一段时间的脚本:

<?php
$samples = "SELECT * FROM materials WHERE materials.type = :cat and materials.supplier = '$supplier'";
$res = $db->prepare($samples);
$res->execute(array(':cat' => $category));
$count = $res->rowCount();
if($count > 0)
echo "
<section class='"border mar_t_40'">
"; 
while ($row = $res -> fetch()){
    $postimggranite = $row[image];
    $postidgranite = $row[id];
    $folder = $row[type];
    $folder = strtolower($folder);
    $supplier = strtolower($supplier);
    $category_id = $row[category_id];
print<<<END
<span class="grid white_back mar_l_30">
<a class="fancybox" href="$img_path/$folder/$supplier/large/$postimggranite" rel="group[$postidgranite]" title="$row[name]"><img alt="$row[name]" src="$img_path/$folder/$supplier/small/$postimggranite" width="100" height="100">$row[name]</a>
</span>
END;
}
echo "<div class='"clearfloat'"></div></section>";
?>

您应该研究Sql Joins。它们是连接两个表的结果所需要的。