一些开发人员使用Laravel和Datatables制作了一个PHP软件。 当我看到应用程序生成的数据库查询时,我发现效率非常低。示例(涉及列的列表从一个软件功能更改为另一个软件功能):
select count(*) as aggregate from (select '1' as [row_count] from [assignments]
left join [jobs] on [assignments].[id] = [jobs].[name]
left join [categories] on [categories].[id] = [jobs].[vol_cat_type]
where ([assignments].[id] LIKE '%XYZ%' or [assignments].[person_id] LIKE '%XYZ%' or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[name_title] LIKE '%XYZ%') >= 1 or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[first_name] LIKE '%XYZ%') >= 1 or
[assignments].[title] LIKE '%XYZ%' or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[gender] LIKE '%XYZ%') >= 1 or
(select count(1) from [states_master] where [states_master].[identity] = [assignments].[current_state] and [states_master].[name] LIKE '%XYZ%') >= 1 or
[assignments].[updated_datetime] LIKE '%XYZ%' or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[nationality] LIKE '%XYZ%') >= 1 or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[place_of_birth] LIKE '%XYZ%') >= 1 or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[civil_status] LIKE '%XYZ%') >= 1 or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[email] LIKE '%XYZ%') >= 1 or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[date_of_birth] LIKE '%XYZ%') >= 1 or
(select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[nationality2] LIKE '%XYZ%') >= 1
or (select count(1) from [people] where [assignments].[person_id] = [people].[person_id] and [people].[skype] LIKE '%XYZ%') >= 1))
count_row_table
涉及的表很大,这些查询不仅需要20-30秒才能执行,而且还会影响服务器的一般性能。 我不喜欢的是许多LIKE应用于所有列,特别是那些应用于非字符串的列(如上次修改日期)。 我的建议是:
1)对于所有非字符串:数字使用=而不是LIKE,使用性别M / F,布尔值等单字符代码
2)配置Microsoft SQL Server中包含的全文搜索,并写入CONTAINS(列,' XYZ')而不是LIKE
开发人员的反对意见是Laravel和Datatables产生了这些查询,我们无能为力。
是否可以配置Laravel和Datatables,当然不需要更改库代码,为每个列指定是使用LIKE,=还是CONTAINS?
答案 0 :(得分:2)
Eloquent通常用于创建更简单的模型查询。
对于更复杂的SQL查询,请使用查询构建器。
这是有关如何使用它的文档中的一个示例。
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
如果您愿意,也可以使用原始SQL。
$results = DB::select('select * from users where id = :id', ['id' => 1]);
参考文献: