我想阻止这个:
$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%'";
是否可以只在一个查询中执行此操作?
答案 0 :(得分:2)
试试这个吗?
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%'
这将导致:
Hours | Executor
----------------
123 | floris
456 | rosa
789 | lotte
答案 1 :(得分:0)
此question向您展示如何将GROUP BY
与LIKE
一起使用...然后您可以执行以下操作:
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
然后你可以在不同的行上匹配exec的小时数。
我链接的那个问题向您展示了更高级的方法,以防您需要做更多这些......
答案 2 :(得分:0)
如果需要每执行者的结果,则以下内容应足够:
SELECT executors, SUM(hours)
FROM logs
WHERE executors LIKE '%floris%'
OR executors LIKE '%rosa%'
OR executors LIKE '%lotte%'
GROUP BY executors
答案 3 :(得分:0)
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;
但是,您知道,在第一个位置使用%
可能会破坏您的数据库性能。因为在那种情况下索引不会使用。尽量避免这种要求。