doukoumi3389 2015-06-30 07:21
浏览 40
已采纳

数据库查询优化(MySql)

I have three tables.

  1. Radar data table (with id as primary), also has two columns of violation_file_id, and violation_speed_id.

  2. Violation_speed table (with id as primary)

  3. violation_file table (with id as primary)

I want to select all radar data, limited by 1000, from some start interval to an end interval, joins with violation_speed table. Each radar data must have a violation_speed_id.

I want to then join with the violation_file table, but not each radar records corresponding to violation_file_id, some records just has violation_file_id of 0, means there's no curresponding file.

My current sql is like this,

$results = DB::table('radar_data')
    ->join('violation_speed', 'radar_data.violation_speed_id', '=', 'violation_speed.id')
    ->leftjoin('violation_video_file', 'radar_data.violation_video_file_id', '=', 'violation_video_file.id')
    ->select('radar_data.id as radar_id',
      'radar_data.violation_video_file_id',
      'radar_data.violation_speed_id',
      'radar_data.speed',
      'radar_data.unit',
      'radar_data.violate',
      'radar_data.created_at',
      'violation_speed.violation_speed',
      'violation_speed.unit as violation_unit',
      'violation_video_file.video_saved',
      'violation_video_file.video_deleted',
      'violation_video_file.video_uploaded',
      'violation_video_file.path',
      'violation_video_file.video_name')
    ->where('radar_data.violate', '=', '1')
    ->orderBy('radar_data.id', 'desc')
    ->offset($from_id)
    ->take($max_length)
    ->get();

It is PHP Laravel. But I think the translation to mysql statement is straight away.

My question is, is it a good way to select data like this? I tried but it seems a bit slow if the radar data grows to a large value.

Thanks.

  • 写回答

2条回答 默认 最新

  • douzen1880 2015-06-30 07:28
    关注

    Assuming you have the proper indices set this is largely the way to go, the only thing that's not 100% clear to me is what the offset() method does, but if it simply adds a WHERE clause than this should give you pretty much the best performance you're going to get. If not, replace it with a where('radar_data.id', '>', $from_id)

    The most important indices are the ones on the foreign keys and primary keys here. And make sure not to forget the violate index.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码