2012-11-30 39 views
1

我在这里有三个表,我试图做一个棘手的组合查询。联合求和MySQL查询问题

表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  

我有两个查询,我试图写 而不是试图总结这些每次我查询吨ickets,我已向ticket添加了weekly_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") 

不仅是查询慢,但它似乎也不会返回总和的分数,它只是返回列表中的第一个分数。

任何帮助,非常感谢。

+1

您不能用逗号分隔列值'(t.teamids)'替代IN()'子句。 MySQL将'IN()'子句中的单个字符串视为IN('150,152,154')',而不是3个不同的值。 –

+2

这里最好的解决方案是正确地规范'tickets'表格,使其包含一行'teamid' –

+0

您应该规范化您的票据表,每个团队和每周记录一个。 – Wolf

回答

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

未测试。

+0

分数表中没有SUM。它每个团队都有一个分数,而每张票可以有4-5个团队分配给它。我在MySQL中并没有那么先进,我从来没有真正使用过JOIN ... – user1866795

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和更多信息的答案)。