结合SUM的MySQL查询问题

时间:2012-11-30 16:01:43

标签: mysql sql

我这里有三张桌子,我正在尝试进行棘手的综合查询。

表1(团队)中有团队:

id     name
------------
150    LA Lakers
151    Boston Celtics
152    NY Knicks

表2(分数)中有分数:

id  teamid   week    score
---------------------------
1     150     5        75
2     151     5        95
3     152     5        112

表3(门票)中有门票

id    teamids    week
---------------------
1   150,152,154   5   
2   151,154,155   5    

我正在尝试编写两个查询 我没有在每次查询故障单时尝试对这些进行求和,而是在故障单中添加了week_score字段。这个想法是,无论何时为团队输入新分数,我都可以获得团队ID,获得具有该团队/周组合的所有门票,并根据团队分数的总和更新所有门票。

我已尝试以下方法来获取我正在寻找的结果(在我尝试更新之前):

SELECT t.id, t.teamids, (
  SELECT SUM( s1.score ) 
  FROM scores s1
  WHERE s1.teamid
   IN (
    t.teamids
   )
 AND s1.week =11
) AS score
FROM tickets t
WHERE t.week =11
AND (t.teamids LIKE  "150,%" OR t.teamids LIKE  "%,150")

查询不仅速度慢,而且似乎也没有返回分数的总和,只返回列表中的第一个分数。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

这里你不需要SUM功能吗?分数表已经有了吗?顺便说一句,避免子查询,尝试左连接(或根据您的需要左外连接)。

SELECT t.id, t.name, t1.score, t2.teamids 
FROM teams t 
LEFT JOIN scores t1 ON t.id = t1.teamid AND t1.week = 11
LEFT JOIN tickets t2 ON t2.week = 11 
WHERE t2.week = 11 AND t2.teamids LIKE "%150%"

未经测试。

答案 1 :(得分:0)

如果您要匹配,则您需要适应仅具有一个团队ID的列。此外,您需要在SELECT子查询中使用LIKE。

SELECT t.id, t.teamids, (
  SELECT SUM( s1.score ) 
  FROM scores s1
  WHERE 
    (s1.teamid LIKE t.teamids 
        OR CONCAT("%,",s1.teamid, "%") LIKE t.teamids 
        OR CONCAT("%",s1.teamid, ",%") LIKE t.teamids
    )
    AND s1.week =11
) AS score
FROM tickets t 
WHERE t.week =11
AND (t.teamids LIKE  "150,%" OR t.teamids LIKE  "%,150" OR t.teamids LIKE "150")

答案 2 :(得分:0)

不是最优雅的查询,但它应该说:

SELECT
  tickets.id,
  tickets.teamids,
  sum(score)
FROM
  tickets left join scores
  on concat(',', tickets.teamids, ',') like concat('%,', scores.teamid, ',%')
WHERE tickets.week = 11 and concat(',', tickets.teamids, ',') like '%,150,%'
GROUP BY tickets.id, tickets.teamids

或者也是这样:

SELECT
  tickets.id,
  tickets.teamids,
  sum(score)
FROM
  tickets left join scores
  on FIND_IN_SET(scores.teamid, tickets.teamids)>0
WHERE tickets.week = 11 and FIND_IN_SET('150', tickets.teamids)>0
GROUP BY tickets.id, tickets.teamids

(请参阅此question以及更多信息的答案)。