【发布时间】:2018-08-10 09:44:38
【问题描述】:
首先我想说我真的是数据库初学者,不要评判我。
我从 web 服务接收到很多参数,我必须使用这些参数进行 sql 查询。问题是我的查询消耗了大量的 cpu,因为我对查询的优化不好。
SELECT
SUM(t.total_amount) as SumaAmount,
COUNT(t.id) as TotalTransaccions
FROM RealTimeVending.dbo.rtv_turnover_transaction as t,
RealTimeVending.dbo.rtv_trans_articles as ta,
RealTimeVending.dbo.articles as art, RealTimeVending.dbo.groups,
RealTimeVending.dbo.Clients as s,
RealTimeVending.dbo.rtv_transactions as tr,
RealTimeVending.dbo.tills as till, RealTimeVending.dbo.Ubicacion as u,
RealTimeVending.dbo.Operadores as o
where t.operador_id=o.ID and t.transaction_id=ta.transaction_id and
art.id=ta.article_id and s.id=t.cliente_id and tr.id=t.transaction_id
and groups.id=art.group_a_id and t.ubicacio_id=u.id
and convert(date,t.trans_date) >='"+globalMap.get("datainici")+"'and
convert(date,t.trans_date) <= '"+globalMap.get("datafinal")+"'and
and (s.codigo IS NULL or s.codigo like '%"+globalMap.get("client")+"%')
and (t.total_amount IS NULL or t.total_amount like'"+globalMap.get("amount")+"%')
想象一下,我将 web 服务中的所有参数都设为空。数据库将花费大量时间处理这些参数。我想做的是一个查询,我可以在其中搜索不为空的参数。例如,如果“t.total_amount”为空,我不想在查询中插入搜索。
我希望你能理解我的问题。非常感谢。
【问题讨论】:
-
作为初学者无需道歉——除了查询、表的模式、表上的索引,理想情况下,任何人都需要查询的查询计划提供具体建议。即使没有这些,
s.codigo like '%"+globalMap.get("client")+"%'也会导致问题,像这样的完整通配符搜索将始终扫描数据 -
今日提示:切换到现代、明确的
JOIN语法!更容易编写(没有错误),更容易阅读和维护,如果需要更容易转换为外连接。 -
此查询使用带有字符串连接的变量而不是参数。我无法评论如何使用
talend正确参数化它,但查询将包含参数标记,其中实际运行时值分别添加到命令中(例如convert(date,t.trans_date) >= ?)。最好重构查询以避免将convert之类的函数应用于列,以便有效地使用索引。
标签: sql sql-server tsql select