I know this will either use a left join
or left outer join
or something like that, but these types of queries always throw me off.
I have two tables:
categories
ID CatName CatSlug
1 Big Shirts big-shirts
items
ID ItemName Category Price ...
1 Big Red Shirt 1 20.00
So I am trying to return all items in a given category, queried by the category slug. I also need to return the category name. So now, my two queries are like:
$return = array();
$query = "SELECT * FROM categories WHERE CatSlug = :CatSlug LIMIT 1";
$param = array(
'CatSlug' => $slug
);
$result = $this->Db->selectOne($query, $param);
if ($result) { // If result exists
$return['Category'] = $result['CatName']; // Need to return cat name
$query = "SELECT * FROM items WHERE Category = :Category";
$param = array(
'Category' => $result['ID']
);
$result = $this->Db->selectAll($query, $param);
if ($result) { // If result exists
$return['Items'] = $result;
} else { // If result does not exist
$return['Items'] = array();
} // End if result does not exist
}
return $return;
So, I am returning an array with two keys: Category
contains the CatName
value in the categories
table, and Items
contains an array of all items inside that category, or a blank array if there are none.
How can I combine these two queries?