2017-01-23 80 views
0

我有一个名为subcategories的表,其中包含列'id'和'name'以及名为目标的表,其中包含列'id','name'和外键'subcategory_id ”。找不到MYSQL查询来获得我想要的结果

我想要一个查询结果的子类别对象的数组,其中有一个属性“目标”,这是一个目标对象的数组。 太给的结果会怎样看在JS代码的例子:

result = [ 
      {id: 1, name: "name", goals: [{id: 1, name: "goalName"}, {...}, {...}]}, 
      {...}, 
      {...} 
     ] 

但是(用不同的语法)的结果将是对其他语言..

相同Thusfar我试图做到这一点与左连接,像这样:

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 

但目标不是一个单一的子类别进行分组。我觉得这应该是可能的查询做的,但我想不出/谷歌如何做到这一点,因为我不知道如何对我的问题进行解释ack of SQL knowledge ..

希望你们能帮助我!

在此先感谢。

+0

上次我检查没有直接访问从JS的MySQL,所以.. – 2017-01-23 19:56:03

+0

有没有办法,单个查询给你以上的结果。根据需要获取所有数据并转换数据。 lodashjs可能是非常有用的工具。如果您在nodejs应用程序中获取数据或将数据发送到浏览器。 – gaurang171

+0

@RC。我只是使用JS格式来说明我想要返回的数组..我使用的NodeJS使用相同的格式 – Guinn

回答

0

最后我解决了这个使用groupBy作为@tadman在他的评论暗示。

我创建了一个功能(基于信息this答案),看起来像这样:

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

导致对象的数组被分组进球!在我现在构造函数时(使用硬编码的键名),它只适用于我的特定情况,如果您想概括可以添加参数的函数并将硬编码的键名替换为那些。

1

您将无法通过查询达到目的。 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; 
} 
+0

我希望你不要在生产代码中这样做,因为使用字符串连接来扼杀你的查询中的东西是可怕的。使用带有占位符值的预准备语句。 Node.js中也可以使用[Sequelize](http://sequelizejs.com)。 – tadman

+0

是的......这就是评论所说的。 “你可能想使用准备好的语句,我只是简化”。 – Gabriel

+0

哦,只有当你滚动时,才能看到,但是没问题。 – tadman

相关问题