我知道这将使用 left join
或left outer join
或类似的东西,但这些类型的查询总是让我失望。
我有两个表:
类别
ID CatName CatSlug
1 Big Shirts big-shirts
项目
ID ItemName Category Price ...
1 Big Red Shirt 1 20.00
因此,我尝试返回给定类别中的所有项目,并由类别 slug 查询。我还需要返回类别名称。所以现在,我的两个查询如下:
$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;
所以,我返回一个带有两个键的数组:Category
包含CatName
categories
中的值表,和 Items
包含该类别内所有项目的数组,如果没有,则包含一个空白数组。
如何组合这两个查询?
最佳答案
- 首先,您应该在表 page_categories 和 items 之间使用 LEFT JOIN。
SELET * FROM page_categories p LEFT JOIN items i ON p.category = i.id WHERE c.CatSlug = :CatSlug
- 循环结果并返回数据
$return['CatName'] = :CatSlug $return['Items'] = array (can be empty array)
关于php - SQL : Combining two select queries, 使用第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383555/