Inefficient SQL Query

前端 未结 5 806
温柔的废话
温柔的废话 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:57

    Besides a single combined query you can use two separate ones.

    You have a basic tree-structure here with branch elements (categories table) and leaf elements (snippets table). The shortcoming of the single-query solution is that you get owner brach-element repeatedly for every single leaf element. This is redundant information and depending on the number of leafs and the amount of information you query from each branch element can produce large amount of additional traffic.

    The two-query solution looks like:

    $navQuery = $mysqli->query ("SELECT id, slug, name FROM categories WHERE live=1 ORDER BY name")
        or die (mysqli_error ($mysqli));
    $subNavQuery = $mysqli->query ("SELECT c.id AS cid, s.id, s.name FROM categories AS c LEFT JOIN snippets AS s ON s.category=c.id WHERE c.live=1 ORDER BY c.name, s.name")
        or die (mysqli_error ($mysqli));
    
    $sub = $subNavQuery->fetch_object ();    // pre-reading one record
    while ($nav = $navQuery->fetch_object ()) {
    
        echo '
  • '; echo ''. $nav->name .''; echo '
      '; while ($sub->cid == $nav->id) { echo '
    • '; echo ''. $sub->name .''; echo '
    • '; $sub = $subNavQuery->fetch_object (); } echo '
    '; }
提交回复
热议问题