开发者

Prevention of mutiple sql sum queries possible?

I would like to prevent this:

开发者_如何学编程  $florissql = "SELECT SUM(hours) FROM logs WHERE executors LIKE '%floris%'";
  $rosasql = "SELECT SUM(hours) FROM logs WHERE executors LIKE '%rosa%'";
  $lottesql = "SELECT SUM(hours) FROM logs WHERE executors LIKE '%lotte%'";

Is it possible to do this in just one query?


Try this maybe?

 SELECT SUM(hours) AS Hours, 'floris' AS Executor FROM logs WHERE executors LIKE '%floris%'
 UNION ALL
 SELECT SUM(hours) AS Hours, 'rosa' AS Executor FROM logs WHERE executors LIKE '%rosa%'
 UNION ALL 
 SELECT SUM(hours) AS Hours, 'lotte' AS Executor FROM logs WHERE executors LIKE '%lotte%'

That'll result in:

  Hours | Executor
  ----------------
  123   | floris
  456   | rosa
  789   | lotte


This question shows you how to use GROUP BY with LIKE... then you can do something like this :

SELECT
  CASE
    WHEN executors LIKE '%floris%'   THEN 'floris'
    WHEN executors LIKE '%rosa%' THEN 'rosa'
    WHEN executors LIKE '%lotte%' THEN 'lotte'
  END AS exec
, SUM(hours) AS hrs
FROM logs
GROUP BY 
  CASE
    WHEN executors LIKE '%floris%'   THEN 'floris'
    WHEN executors LIKE '%rosa%' THEN 'rosa'
    WHEN executors LIKE '%lotte%' THEN 'lotte'
  END

Then you can match the sum of hours with exec on the different rows.

That question I linked to shows you more advanced methods to in case you need to do more of those...


If results per executor are required, the following should suffice:

SELECT executors, SUM(hours)
FROM logs
WHERE executors LIKE '%floris%'
OR executors LIKE '%rosa%'
OR executors LIKE '%lotte%'
GROUP BY executors


SELECT 
    sum(IF(executors LIKE '%floris%',hours,0)) as 'floris',
    sum(IF(executors LIKE '%rosa%',hours,0)) as 'rosa',
    sum(IF(executors LIKE '%lotte%',hours,0)) as 'lotte'
FROM logs;

But, you know, usage % at first position could kill you DB performance. Because in that case indexes will not using. Try to avoid that kind of requests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜