【问题标题】:Muliple Joins sum values based on two different critiea with sort多个连接根据两个不同的标准对值进行排序
【发布时间】:2012-04-13 06:51:25
【问题描述】:

我有一个有 4 个表的数据库。

Table 1 - "company" table with company_id as the key
Table 2 - "users" table with the user_id as the key
Table 3 - "teams" table that references the company_id and the user_id (So that user can belong to multiple teams.
Table 4 - "points" table that references the company_id, the user_id, points_earned (Numeric value of points given), exchange_dte (0 - if the user has not used the points, otherwise a unixtime value)

给定一个已知的 company_id,我正在尝试呼叫属于该“团队”的所有用户,并显示他们的总积分和未交换的积分。以下 MySQL 将只提供公司 #1 团队的第一个用户。目前数据库中有 5 位用户都获得了一定数量的积分,有的交换了,有的没有。

SELECT 
users.user_id AS u_id, 
SUM(points.points_earned) AS ttl_points,
SUM(case when exchange_dte = '0' then points.points_earned else 0 end) AS unused_points
FROM users
INNER JOIN teams ON teams.user_id = users.user_id
INNER JOIN points ON points.user_id = users.user_id
WHERE (teams.company_id = '1' AND points.company_id = '1' AND users.user_active = '1');

然后我尝试将 user_id 添加到 Sum 调用中。最终得到同样的结果。

SELECT
users.user_id AS u_id, 
SUM(case when points.user_id = users.user_id then points.points_earned else 0 end) AS ttl_points,
SUM(case when points.exchange_dte = '0' AND points.user_id = users.user_id then points.points_earned else 0 end) AS unused_points
FROM users
INNER JOIN teams ON teams.user_id = users.user_id
INNER JOIN points ON points.user_id = users.user_id
WHERE (teams.company_id = '1' AND points.company_id = '1' AND users.user_active = '1')
ORDER BY ttl_points;

有趣的是,第一个用户的总点数似乎是数据库中的所有点数,即使他们有关联的 user_id 和 company_id

想法?

【问题讨论】:

  • @user1330742 好的,我不知道您需要权限才能编辑自己的问题。

标签: php mysql


【解决方案1】:

您尝试在不使用 GROUP BY 的情况下进行 SUM:不确定它是否适合您,但请尝试在查询结束后添加 GROUP BY users.user_id,看看是否对您有帮助。

SELECT
users.user_id AS u_id, 
SUM(case when points.user_id = users.user_id then points.points_earned else 0 end) AS ttl_points,
SUM(case when points.exchange_dte = '0' AND points.user_id = users.user_id then points.points_earned else 0 end) AS unused_points
FROM users
INNER JOIN teams ON teams.user_id = users.user_id
INNER JOIN points ON points.user_id = users.user_id
WHERE (teams.company_id = '1' AND points.company_id = '1' AND users.user_active = '1') GROUP BY users.user_id
ORDER BY ttl_points;

【讨论】:

  • 谢谢,完美解决了。这是我第一次在 MySQL 语句中尝试 SUM。谢谢你也解释了我错过了什么。
  • 很高兴它有帮助。聚合总是在您遇到它的前几次时令人困惑,而且我之前肯定被那个错误所困扰。
  • 最后一个问题。如果用户在数据库中没有累积任何积分,则他们不会显示。
  • 您可能想用LEFT JOIN 替换积分表上的INNER JOIN:试试看它是否有效。但不确定它的效果如何。
  • 给我同样的结果。用户实际上是被列出的,因为当用 php 循环结果时,我得到一个空白行,只是没有得到 user_id。我可以检查以显示两组点的“0”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多