mysql join从2行获取信息

时间:2014-04-29 21:56:07

标签: mysql join

我有两张桌子:

players
id  |  dni | name
-----------------  
1      222    mike
2      333    gerard
3      444    mark
4      555    alfred
5      666    thomas
5      777    nicolas

teams
id  |  dni1 | dni2 | cat 
------------------------  
1      222    333    1
2      444    555    1
3      666    333    2
4      777    222    2

我想要的是根据猫做一个选择语句。所以

cat = 1应该是:

迈克杰拉德 mark alfred

并且对于cat = 2应该是:

托马斯杰拉德 尼古拉斯迈克
我尝试了许多加入声明,但我无法弄清楚,你能帮帮我吗?

编辑使其更难,玩家表有一个新的colum = points

players
    id  |  dni | name | points
    --------------------------  
    1      222    mike     1
    2      333    gerard   2
    3      444    mark     3
    4      555    alfred   4
    5      666    thomas   5
    5      777    nicolas  6

现在结果给出了两个玩家的积分和最大总数的顺序之和。 cat = 1应该是:

mark alfred 7
迈克杰拉德3

1 个答案:

答案 0 :(得分:0)

select t.cat, p1.name name1, p2.name name2, p1.points + p2.points points
from teams AS t
join players AS p1 ON p1.dni = t.dni1
join players AS p2 on p2.dni = t.dni2
where cat = 1
order by points desc

DEMO