简体   繁体   English

内部连接mysql表

[英]inner join mysql tables

Ok here it is. 好的,这是。 i have two tables: products and product_sizes 我有两个表:product和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): 在这里,我有一个工作代码来显示产品表(使用while代码的html):

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. 对不起,我的解释是我的英语不好。

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 . 请参阅此链接,直观地表示各种JOIN

<? 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>
<? } ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM