简体   繁体   English

使查询效率更高

[英]Make this query more efficient

I'm terrible at writing queries that are dealing with large datasets. 我在编写处理大型数据集的查询时很糟糕。 I wanted to take a stab at Laravel and see what I can come up with. 我想在Laravel一口,看看我能想到什么。 Is there a better way to write this query and output the results? 有没有更好的方法编写此查询并输出结果?

Code

$visitors = DB::table('visitors')
            ->where('id_client',1)
            ->select('id', 'ip', DB::raw('count(*) as total'), 'date', 'city', 'region')
            ->groupBy('ip')
            ->orderBy('date', 'DESC')
            ->simplePaginate(25);

Results 结果

@foreach($visitors as $visitor)
               <tr>
                        <td>
                            {{$visitor->id}}
                        </td>
                        <td>
                            @if (date('F d, Y', strtotime($visitor->date)) === date('F d, Y'))
                                Today
                            @else
                                {{ date('F d, Y', strtotime($visitor->date)) }}
                            @endif  
                        </td> 
                        <td>
                            {{$visitor-total}}
                        </td>                       
                        <td>
                            {{$visitor->city}}
                        </td>
                        <td>
                            {{$visitor->region}}
                        </td>
                 </tr>
          @endforeach

          {!! $visitors->render() !!}

Also, I get the error Use of undefined constant total - assumed 'total' when I try to load the page. 另外,当我尝试加载页面时,我得到错误Use of undefined constant total - assumed 'total'

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

The query looks good as long as it does what you need. 只要查询满足您的需求,它就看起来不错。

If your query runs too slow, maybe you can add an index to your 'id_client' column to make the search faster (if you don't have it already of course). 如果查询运行太慢,则可以将索引添加到“ id_client”列中,以加快搜索速度(当然,如果您还没有的话)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM