2014-08-30 133 views
0

在我的表格中,我拥有玩家的唯一ID(玩家_1,玩家_2,玩家_3,玩家_4,玩家_5),并在我的表格“玩家”中标识玩家的名字。例如,在搜索脚本的情况下(按名称搜索):MySQL通过ID加入2张表

The user write "foo" but "foo" is ID 20. 

"teams" ID 1 => player_1 ID = 20 
"players" player_id = 20 > name = foo 

这里是我的查询:

$sql = 'SELECT * FROM teams LEFT JOIN players ON players.name LIKE :word'; 

但正如我wan't它没有工作......

+0

您需要一个条件表达式。请参阅http://dev.mysql.com/doc/refman/5.1/en/join.html :) ... p.s.你的LIKE表达式看起来也是连线的(查看http://dev.mysql.com/doc/refman/5.1/en/string-comparison-functions.html) – Trinimon 2014-08-30 08:40:26

+0

'ON'应该被用来连接两个表,你应该给出用于连接表的列,'WHERE'条件是你比较列和字符串时需要的 – Fabio 2014-08-30 08:40:48

回答

0

请尝试以下查询

select * from teams as tm,players as py where tm.player_1=py.player_id and py.name LIKE 'foo%' 

为什么你需要加入团队表?您只能使用玩家表进行搜索。

0

加入的ID = player_id和按名称搜索:

select * from teams join players on player_id = ID where name like 'Adam%'; 
+-----------+---------+----+---------+ 
| player_id | team_id | ID | name | 
+-----------+---------+----+---------+ 
|   1 |  1 | 1 | Adam G. | 
|   3 |  2 | 3 | Adam S. | 
+-----------+---------+----+---------+ 

sqlfiddle

如果两个表中使用相同的字段名称,你可以加入基于列:

select * from teams join players using (player_id) where name like '%S.'; 
+-----------+---------+---------+ 
| player_id | team_id | name | 
+-----------+---------+---------+ 
|   3 |  2 | Adam S. | 
|   5 |  1 | Jim S. | 
+-----------+---------+---------+ 
2 rows in set (0.01 sec) 

​​