我遇到了加入mysql的问题,我试图在订单表中的band_id与来自band表的Band_id匹配时,将order表中的Name字段填充到orders表中的band_name字段。 这一切都令人困惑,并希望得到一些建议或帮助。
我的代码
<?php
}
$user = new User();
$user_name = escape($user->data()->username);
$result = mysql_query("SELECT bands.Name FROM bands LEFT JOIN orders ON bands.Band_id = orders.band_id WHERE orders.band_id = 1 AND user_name = '"mysql_real_escape_string($user_name)"'");
//$result = mysql_query("SELECT * FROM orders WHERE user_name = '".mysql_real_escape_string($user_name)."'");
echo '<table border="1">
<tr>
<th>My bookings</th>
<th>gig No</th>
</tr>';
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
echo
"<tr>
<td>".$row['user_name']."</td>
<td>".$row['band_id']."</td>
</tr>";
}
}else{
echo "<tr><td>No bookings</td></tr>";
}
echo "</table>";
?>
答案 0 :(得分:2)
SELECT * FROM bands
LEFT JOIN orders as user_orders ON(
user_orders.band_id = bands.band_id
AND user_orders.user_name = "'.mysql_real_escape_string($user_name).'"
)
答案 1 :(得分:1)
我认为你接近你对DB的使用有点不对。
您的bands
表格应包含乐队所需的所有信息。比如这个:
| id | name |
====================
| 1 | The Beatles |
| 2 | Blur |
etc
您的orders
表应包含所有或您的订单数据:
| id | band_id |
================
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
如你所见,甲壳虫乐队有2个订单,Blur有1个订单。
你可以获得这样的订单的乐队名称:
SELECT bands.name FROM orders, bands, WHERE orders.id = 1 AND orders.band_id = bands.id;
使用内部联接:
SELECT bands.name FROM bands INNER JOIN orders ON bands.id = orders.band_id WHERE orders.id = 1;
使用左连接:
SELECT bands.name FROM bands LEFT JOIN orders ON bands.id = orders.band_id WHERE orders.id = 1;
更新:
有关联接的更多详细信息,请参阅此图像: