我有一个名为子类别的表,其中包含"id"和"name"列,以及一个名为目标的表,其中包含"id","name"和外键"subcategory_id"。
我想要一个查询,该查询生成一个子类别对象数组,该数组具有属性"goals",它是目标对象的数组。也举一个示例,说明结果在JS代码中的外观:
result = [
{id: 1, name: "name", goals: [{id: 1, name: "goalName"}, {...}, {...}]},
{...},
{...}
]
但是(使用不同的语法)对于其他语言的结果将是相同的。
到目前为止,我尝试使用左连接来执行此操作,如下所示:
SELECT sc.ID as subcatId, sc.name as subcatName, g.ID as ID, g.name as name
FROM needs_subcategories as sc
LEFT JOIN needs_goals as g
ON sc.ID=g.subcategory_id
但是目标并没有归入一个子类别。我觉得应该可以通过查询来做,但我无法弄清楚/谷歌如何做到这一点,因为由于我缺乏SQL知识,我不知道如何表达这个问题。
希望你们能帮助我!
提前谢谢。
您将无法使用查询来实现这一点。MySQL不能做到这一点。
您当前正在获取所有目标,每个目标都有其子类别(子类别将重复)。
您可以使用一些代码将其转换为所需的数组(例如在 php 中,您可以将其翻译成任何其他语言)。
$result=array();
$lastSubcatId=null;
$goals=array();
while($row=$query->fetch_object()) { //assuming $query is the resultset
if($lastSubcatId&&$lastSubcatId!=$row->subcatId) {
$row->goals=$goals;
$result[]=$row; //or you could assign each desired property
$goals=array();
}
$goals[]=$row; //or you could assign each desired property
}
//surely, there are items left in $goals
if($lastSubcatId) {
$row->goals=$goals;
$result[]=$row; //or you could assign each desired property
}
但我认为,更有效的方法是使用多个查询:
$result=array();
$subcats=$db->query("SELECT * FROM needs_subcategories");
while($subcat=$subcats->fetch_object()) {
//you might want to use prepared statements, I'm just simplifying
//it will not only be safer, but reusing the prepared statement will increase the performance considerably
$goals=$db->query("select * from needs_goals where subcategory_id=".$subcat->ID);
$temp=array();
while($goal=$goals->fetch_object()) $temp[]=$goal;
$subcat->goals=$temp;
$result[]=$subcat;
}
最后,我按照@tadman评论中的建议使用 groupBy 解决了这个问题。
我创建了一个函数(基于此答案中的信息),如下所示:
function processResults(collection, groupKey) {
var result = _.chain(collection)
.groupBy(groupKey)
.toPairs()
.map(function (currentItem) {
// 'text' and 'children' are the keys I want in my resulting object
// children being the property that contains the array of goal objects
return _.zipObject(['text', 'children'], currentItem);
})
.value();
return result;
}
这会导致具有分组目标的对象数组!由于我现在构建了函数(使用硬编码的键名),它仅适用于我的具体情况,如果您想概括函数,您可以添加参数并用这些参数替换硬编码的键名。