MySQL按ID加入2个表

时间:2014-08-30 08:35:45

标签: mysql join

在我的表“团队”中,我有玩家的唯一ID(player_1,player_2,player_3,player_4,player_5),在我的表“玩家”中,这些ID是玩家的名字。例如,在搜索脚本案例中(按名称搜索):

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';

但它不起作用,因为我不...

2 个答案:

答案 0 :(得分:0)

尝试以下查询

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

为什么你需要加入团队表?您只能使用玩家表格按名称搜索。

答案 1 :(得分: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)

sqlfiddle