php - 来自多个表的 MySQL SUM

标签 php mysql sql

我有 2 个表:'sending_fresh' 和 'agents'

我想从“sending_fresh”中获取“cc”等于某个日期的总数,并从“代理”中获取特定团队。

我目前有:

SELECT SUM(sending_fresh.cc), agents.team  
FROM sending_fresh, agents 
WHERE agents.team = 'team1' 
AND sending_fresh.date = '2012-05-12'

当仅从“sending_fresh”表中选择时,总和工作正常,但当从第二个表中添加 WHERE 语句时,结果会更高且错误。

有人能帮忙吗?

最佳答案

主要答案

The foreign key in sending_fresh is agent_id which corresponds to id in the agents table.

您缺少 JOIN 条件并且缺少 GROUP BY 子句:

SELECT SUM(s.cc), a.team  
  FROM sending_fresh AS s
  JOIN agents        AS a ON a.id = s.agent_id
 WHERE a.team = 'team1' 
   AND s.date = '2012-05-12'
 GROUP BY a.team;

在我们获得有关加入的信息之前,我写道:

SELECT SUM(s.cc), a.team  
  FROM sending_fresh AS s
  JOIN agents        AS a ON a.team = s.team    -- Guess at join columns!
 WHERE a.team = 'team1' 
   AND s.date = '2012-05-12'
 GROUP BY a.team;

由于您错过了连接条件,我不得不猜测它是什么。它可能会变成 a.team_id = s.team_id 或类似的东西。

如果加入是在 sending_fresh.team 上,您可以根据需要完全避免加入。

SELECT SUM(cc), team  
  FROM sending_fresh
 WHERE team = 'team1' 
   AND date = '2012-05-12'
 GROUP BY team;

现在该模式已更详细地为人所知,这种简化是无效的。


一般评论

请注意,使用显式 JOIN 意味着您不应忘记连接条件。您不应在 FROM 子句中使用表表示法的逗号列表。您需要了解它才能识别古老的 SQL。你不应该在新的 SQL 中使用它,你应该升级旧的 SQL 以使用显式连接。

请注意,如果您在查询中有 N 个表,则应该有 N-1 个连接条件。

关于php - 来自多个表的 MySQL SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11477679/

相关文章:

javascript - 如何将数据从sql传输到javascript?

MySQL 为其中的每个 id 获取最新的 3 行

mysql - 基于参数的 Rails DB

mysql - 使用 COUNT() 查找另一个表中存在多少行

sql - 计算多个日期的运行总计

需要 SQL Server 2017 多维模式

javascript - 如何优化我的加载 JQuery 函数?

php - Cakephp 和 iOS 10.3.2

php - 如何创建雅虎 smtp 服务器的套接字?

php - 在 PHP 中使用 MAX 和 SUBSTRING_INDEX 的 SQL 查询