Inefficient SQL Query

前端 未结 5 829
温柔的废话
温柔的废话 2021-02-19 08:08

I\'m building a simple web app at the moment that I\'ll one day open source. As it stands at the moment, the nav is generated on every page load (which will change to be cached

5条回答
  •  借酒劲吻你
    2021-02-19 08:53

    First off, you shouldn't query your database in your view. That would be mixing your business logic and your presentation logic. Just assign the query results to a variable in your controller and iterate through it.

    As for the query, yup a join can do that in 1 query.

    SELECT * -- Make sure you only select the fields you want. Might need to use aliases to avoid conflict
    FROM snippets S LEFT JOIN categiries C ON S.category = C.id
    WHERE live = 1
    ORDER BY S.category, C.name
    

    This will get you an initial result set. But this won't give you the data nicely ordered like you expect. You'll need to use a bit of PHP to group it into some arrays that you can use in your loops.

    Something along the lines of

    $categories = array();
    foreach ($results as $result) {
       $snippet = array();
       //assign all the snippet related data into this var
    
      if (isset($categories[$result['snippets.category']])) {
    
        $categories[$result['snippets.category']]['snippet'][] = $snippet;
      } else {
        $category = array();
        //assign all the category related data into this var;
    
        $categories[$result['snippets.category']]['snippet']  = array($snippet);
        $categories[$result['snippets.category']]['category'] = $category;
      }
    }
    

    This should give you an array of categories which have all the related snippets in an array. You can simply loop through this array to reproduce your list.

提交回复
热议问题