2014-08-30 116 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) 

​​