-1

我有两张桌子

表 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

4 回答 4

1

将类别名称添加到选择查询返回的列中:

$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
            ";
于 2013-04-19T11:07:48.743 回答
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

于 2013-04-19T11:07:57.683 回答
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
            ";
于 2013-04-19T11:05:34.610 回答
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

对特定结果使用内连接

于 2013-04-19T11:09:28.687 回答