SQL Select Statement joining [duplicate]

纵然是瞬间 提交于 2020-01-07 09:33:13

问题


I have one table of oc_category_description where columns are :

  • category_id
  • name

and other table oc_category where columns are :

  • category_id
  • image
  • parent_id

Here the sample pic of oc_category_description table

oc_category table

Here i am want to show name, category_id, image, parent_id where oc_category parent_id is 0;

Here is 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;
}

but it returns nothing :(


回答1:


Use Join

SELECT ocd.category_id, image, parent_id, name
FROM oc_category_description  AS ocd
INNER JOIN oc_category 
WHERE parent_id = 0 
ORDER BY ocd.category_id ASC



回答2:


With an INNER JOIN:

SELECT d.category_id, c.image, c.parent_id, d.name
FROM oc_category_description  d INNER JOIN oc_category c
ON c.category_id = d.category_id
WHERE c.parent_id = 0 
ORDER BY d.category_id

If you get duplicate rows in the results change to:

SELECT DISTINCT...


来源:https://stackoverflow.com/questions/59518953/sql-select-statement-joining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!