小编典典

使用选择语句的SQL连接查询

sql

我有一个oc_category_description表,其中的列是:

  • category_id
  • name

和其他表oc_category,其中的列是:

  • category_id
  • image
  • parent_id

在这里,我想显示名称,category_id,image,parent_id,其中oc_category parent_id为0;

这是sql:

的PHP

function getMainCategory()
{
    $stmt = $this->con->prepare("SELECT category_id, image, parent_id, (SELECT oc_category_description.name FROM oc_category_description WHERE oc_category.category_id = oc_category_description.category_id) FROM oc_category WHERE parent_id = 0 ORDER BY category_id ASC");

    $stmt->execute();
    $stmt->bind_result($category_id, $image, $parent_id, $name);

    $users = array();

    while ($stmt->fetch()) {
        $temp = array();
        $temp['category_id'] = $category_id;
        $temp['image'] = $image;
        $temp['parent_id'] = $parent_id;
        $temp['name'] = $name;

        array_push($users, $temp);
    }
    return $users;
}

但它什么也没返回:(


阅读 143

收藏
2021-04-14

共1个答案

小编典典

请尝试以下脚本-

SELECT oc_category.category_id, 
oc_category.image, 
oc_category.parent_id, 
oc_category_description.name
FROM oc_category 
INNER JOIN oc_category_description 
    ON oc_category.category_id = oc_category_description.category_id
WHERE oc_category.parent_id = 0 
ORDER BY oc_category.category_id ASC
2021-04-14