查询多个表?

时间:2013-07-20 13:38:35

标签: mysql sql

我需要创建一个从同一个数据库中的三个表中读取的查询。

表:

1. cm_players
player_id
card_no
club_id
surname
name
birthdate

2. cm_clubs
club_id
prefix
name
address
place
stadium_id
telephone
fax
email
web
contact_person
president
secretary
press_officer
status
image

3. cm_registrations
player_id
surname
name
birthdate
birthplace
club_id
date_from
date_to
amateur
status

所以,我需要显示

cm_players.name, 
cm_players.surname, 
cm_clubs.name, 
cm_players.birthdate, 
cm_players.card_no,

将cm_players与cm_clubs联系以获取俱乐部的名称,如果用户处于活动状态,请检查cm_registrations .....

我尝试过类似的事情:

SELECT cm_players.name, cm_players.surname, cm_clubs.name, cm_players.birthdate, cm_players.card_no, cm_registrations.amateur FROM cm_players 
INNER JOIN cm_clubs on cm_players.club_id = cm_clubs.club_id, cm_registrations 
WHERE cm_players.name LIKE '%$name%' AND cm_players.surname LIKE '%$surname%' AND cm_players.player_id = cm_registrations.player_id AND cm_registrations.amateur = 0 ORDER BY cm_players.player_id ASC

但没有运气......

任何人都可以帮我构建此查询吗?

2 个答案:

答案 0 :(得分:0)

cm_registrations WHERE cm_players.name LIKE'%$ name%'AND cm_players.surname LIKE'%$ surname%'AND cm_players.player_id = cm_registrations.player_id AND cm_registrations.amateur = 0 ORDER BY cm_players.player_id ASC 加入你使用后错误,而不是cm_registeration更改它并尝试修复它。

答案 1 :(得分:0)

我们在这里设置表别名,并使用该表的相应别名来获取列值,我们使用两个表上的内部联接即俱乐部和注册

SELECT cmp.name, cmp.surname, cmc.name, cmp.birthdate, cmp.card_no, cmr.amateur 
  FROM cm_players cmp 
  INNER JOIN cm_clubs cmc on cmp.club_id = cmc.club_id
  INNER JOIN cm_registrations cmr on cmp.player_id = cmr.player_id
  WHERE cmp.name LIKE '%$name%' 
  AND cmp.surname LIKE '%$surname%' 
  AND cmr.amateur = 0 
  ORDER BY cmp.player_id ASC