在Php中加入两个表

时间:2013-04-19 11:03:48

标签: php mysql join

我有两张桌子

表1类别

Id    name      img   
1   appliances   
2   books

表2产品

ID  name des  price  cataegory sub  img
1  TV    lcd  125     1        tv

我正在尝试加入表2中类别中的两个表,直到从表1中获取名称

这是我的代码

    $sql = "SELECT p.id, 
                   p.name,
                   p.description, 
                   p.price,
                   c.name,
                   p.sub
            FROM products p
            JOIN category c on products p = c.id
            ORDER by p.id
            ";

    if($query =  mysql_query($sql) or die())
    {
        while($result = mysql_fetch_assoc($query))
        {   echo "<tr id='id'>";
            //echo "<td>".$result['img']."</td>";
            echo "<td>".$result['name']."</td>";
            echo "<td>".$result['description']."</td>";
            echo "<td>".$result['price']."</td>";
            echo "<td>".$result['category']."</td>";
            echo "<td>".$result['sub']."</td>";
            echo "</tr>";
        }
    }       ";

4 个答案:

答案 0 :(得分:1)

将类别名称添加到select query:

返回的列中
$sql = "SELECT p.id, 
                   p.name,
                   p.description, 
                   p.price,
                   c.name,
                   p.sub,
                   c.name AS category_name       -- Category name
            FROM products p
            JOIN category c on p.category = c.id
            ORDER by p.id
            ";

答案 1 :(得分:1)

在输出中重命名字段名称:

$sql = "SELECT p.id, 
                   p.name,
                   p.description, 
                   p.price,
                   c.name AS OTHER_NAME,
                   p.sub
            FROM products p
            JOIN category c on p.category = c.id
            ORDER by p.id";

然后获取 OTHER_NAME

答案 2 :(得分:0)

$sql = "SELECT p.id, 
                   p.name,
                   p.description, 
                   p.price,
                   c.name,
                   p.sub
            FROM products p
            JOIN category c on p.cataegory = c.id
            ORDER by p.id
            ";

答案 3 :(得分:0)

您的查询应该是这样的

SELECT
  p.id,
  p.name,
  p.description,
  p.price,
  c.name,
  p.sub
FROM products p
  INNER JOIN c.category
    on products p.cataegory = c.id
ORDER by p.id

使用内部联接获取特定结果