0

我有一张名为玩家的桌子

p_id | first    | last
========================
1    | Michael  | Jordan
2    | Charles  | Barkley
3    | Kobe     | Bryant
4    | Allen    | Iverson
5    | Kevin    | Garnett

然后我有一个名为users的表

u_id | user | player_1 | player_2 | player_3
============================================
1    | John | 1        | 2        | 5
2    | Jane | 3        | 4        | 5
3    | Jim  | 2        | 3        | 4

通过网站上的表格,用户选择他们的球员(字段:player_1,player_2,player_3对应于players表中的id

我正在尝试运行 INNER JOIN,在其中打印用户表中的用户及其玩家选择(第一个,最后一个)

到目前为止我有这个

SELECT * FROM users 
INNER JOIN players p1 ON player_1 = p1.player_id                
INNER JOIN players p2 ON player_2 = p2.player_id                
INNER JOIN players p3 ON player_3 = p3.player_id                
INNER JOIN players p4 ON player_4 = p4.player_id                
INNER JOIN players p5 ON player_5 = p5.player_id                
ORDER BY data";

当我跑

while ($row = mysql_fetch_assoc($result_users))
{
$player_1_first = $row['player_name'];      
$player_1_last = $row['player_last'];

echo $player_1_first." ".$player_2_last;
}

我只得到用户的最后一个选择。

我的问题: 我如何才能正确地完成我想要实现的目标?

4

2 回答 2

0

这是一个可能的解决方案:

SELECT users.*, p1.player_id AS player1_id, p2.player_id AS player2_id, p3.player_id AS player3_id, p4.player_id AS player4_id, p5.player_id AS player5_id FROM users 
INNER JOIN players p1 ON player_1 = p1.player_id                
INNER JOIN players p2 ON player_2 = p2.player_id                
INNER JOIN players p3 ON player_3 = p3.player_id                
INNER JOIN players p4 ON player_4 = p4.player_id                
INNER JOIN players p5 ON player_5 = p5.player_id                
ORDER BY data";

在您的 PHP 代码中,您当然会按名称选择字段,因为它们在 Select 子句中被“重命名”。

但是你也应该修改你的数据库模式,因为一个好的模式不会有这个问题。

于 2013-04-23T16:39:24.333 回答
0

如果我了解您所追求的(您并没有真正说),您需要更改选择以请求您想要的输出

SELECT users.FieldsYouWant, 
p1.first as p1first, p1.last as p1last, 
p2.first as p2first, p2.last as p2last,
p3.first as p3first, p3.last as p3last, 
p4.first as p4first, p4.last as p4last, 
p5.first as p5first, p5.last as p5last 
FROM users 
INNER JOIN players p1 ON player_1 = p1.player_id                
INNER JOIN players p2 ON player_2 = p2.player_id                
INNER JOIN players p3 ON player_3 = p3.player_id                
INNER JOIN players p4 ON player_4 = p4.player_id                
INNER JOIN players p5 ON player_5 = p5.player_id                
ORDER BY data";  

然后在您的输出中,在一行中读取所有 5 个名称请注意,如果用户没有选择 5 个玩家,您将一无所获

于 2013-04-23T16:39:38.143 回答