自我加入加上另一个加入

时间:2012-03-27 13:25:58

标签: mysql

我有一个国家队的表格

id  country  group
1   Poland   1
2   Greece   1
3   England  2
4   France   2
5   Germany  3
6   Spain    3

我也是每个国家的得分表

fromId  score
1       100
3       50
2       90
4       60

我想要做的是回复一个群组中每个国家/地区的分数表,只提供一个国家/地区名称。例如,如果我提供“法国”,那么我想要下面的表格

country   score
England   50
France    60

我已设法通过

自行加入国家/地区表格
SELECT
`t1`.`fldCountry`,
`t1`.`fldID`
FROM tblteam t1, tblteam t2
WHERE
t2.fldTeam = t1.fldTeam
AND
t2.fldCountry = 'France'

但我现在陷入困境,如何加入这个来获取数据!

请有人帮忙吗?

3 个答案:

答案 0 :(得分:1)

你去吧

国家/地区表:

CREATE TEMPORARY TABLE Country
    (
      id INT,
      country VARCHAR(20),
      grp INT
    )
INSERT  INTO  Country
        (
          id,
          country,
          grp
        )
        SELECT  1,
                'Poland',
                1
        UNION ALL
        SELECT  2,
                'Greece',
                1
        UNION ALL
        SELECT  3,
                'England',
                2
        UNION ALL
        SELECT  4,
                'France',
                2
        UNION ALL
        SELECT  5,
                'Germany',
                3
        UNION ALL
        SELECT  6,
                'Spain',
                3 

得分表:

CREATE TEMPORARY TABLE Score ( fromid INT, score INT )
INSERT  INTO Score
        (
          fromid,
          score
        )
        SELECT  1,
                100
        UNION ALL
        SELECT  3,
                50
        UNION ALL
        SELECT  2,
                90
        UNION ALL
        SELECT  4,
                60 

查询:

SELECT  b.country,
        IFNULL(s.score, 0) score
FROM    Country a
        INNER JOIN Country b
            ON a.grp = b.grp
        LEFT JOIN score s
            ON s.fromid = b.id
WHERE   a.country = 'France'

<强>结果:

Country      Score
England      50
France       60

答案 1 :(得分:0)

SELECT
    c.country,
    s.score
FROM
    countries c
    INNER JOIN scores s ON c.id = s.fromId
WHERE
    c.group = (SELECT group FROM countries WHERE country = 'France' LIMIT 1);

答案 2 :(得分:0)

这样的事情应该有效。

Select C2.Country,SUM(S.Score)
FROM Country AS C1 
INNER JOIN Country AS C2
ON C1.Group=C2.Group
INNER JOIN Scores AS S
ON C2.id = S.FromID 
WHERE C1.Country=@Country
GROUP BY C2.Country

@Country是您要查找的国家/地区,在您的情况下,法国。