php 内连接mysql表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3844435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
inner join mysql tables
提问by kester martinez
Ok here it is. i have two tables: products and product_sizes
好的,就在这里。我有两个表:products 和 product_sizes
so basically my product table has id(primary key),name(product name)and size_id(foreign key from product_sizes)
所以基本上我的产品表有 id(主键)、名称(产品名称)和 size_id(来自 product_sizes 的外键)
my product_sizes table has predetermined values:
我的 product_sizes 表具有预定值:
size_id name
------------------
1 1x1
2 2x2
3 3x3
and here i have a working code displaying the product tables(in html using while code):
在这里我有一个显示产品表的工作代码(在 html 中使用 while 代码):
id name size_id
-----------------------------
1 product 1 1
2 product 2 2
3 product 3 1
my problem is that i want to display(in html) the size name rather than its size_id, something similar to these example:
我的问题是我想显示(在 html 中)大小名称而不是它的 size_id,类似于以下示例:
id name size_id
-----------------------------
1 product 1 1x1
2 product 2 2x2
3 product 3 1x1
can someone teach me how to do this?.. i need it urgently for my final project. thank you. sorry for my explanation im not good in english.
有人可以教我怎么做吗?..我的最终项目急需它。谢谢你。抱歉我的解释我英语不好。
采纳答案by OMG Ponies
Use a JOIN:
使用连接:
SELECT p.id,
p.name,
ps.name AS size_name
FROM PRODUCT p
JOIN PRODUCT_SIZES ps ON ps.size_id = p.size_id
See this link of a visual representation of the various JOINs.
<? include ("conn.php");
$sql = "SELECT p.id,
p.name,
ps.name AS size_name
FROM PRODUCT p
JOIN PRODUCT_SIZES ps ON ps.size_id = p.size_id";
$result = mysql_query($sql, $connection) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
?>
<tr>
<td><? echo $row['id']; ?></td>
<td><? echo $row['name']; ?></td>
<td><? echo $row['size_name']; ?></td>
</tr>
<? } ?>