1

我在这里有三个表,我正在尝试对其进行复杂的组合查询。

表 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(tickets) 里面有门票

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

我有两个要尝试编写的查询,而不是每次查询票时都尝试对这些求和,而是在票中添加了一个每周分数字段。这个想法是,每当为团队输入新分数时,我都可以获取该团队 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")

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

任何帮助是极大的赞赏。

4

3 回答 3

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%"

未测试。

于 2012-11-30T16:12:32.350 回答
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")
于 2012-11-30T16:15:06.623 回答
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

(有关更多信息,请参阅此问题和答案)。

于 2012-11-30T18:46:13.287 回答