我有两个桌子
wp_divisions
(id,div_id {fk},player_id {fk},div_name)
wp_players
(id {pk},播放器,单元格,电子邮件)。
wp_divisions:
1,1001,23, 3.5 Singles
2,1001,34, 3.5 Singles
3,1001,43, 3.5 Singles
4,1003,54, 4.5 Singles
5,1003,56, 4.5 Singles
wp_players:
23, Eric Simmons, 2135551234, eric@gmail.com
34, Michael Bass, 2134534321, mike@gmail.com
43, Jeff Bowman, 2134542324, jeff@gmail.com
54, Peter Pumpkin, 2137893434, pete@gmail.com
56, Jeremy Smith, 2138983465, jeremy@gmail.com
杰里米(Jeremy)登录该网站,并且应该只在表中看到与其div_id相关的球员。
我可以跑步
SELECT * FROM wp_div d WHERE d.div_id = 1001;
我得到:
4,1003,54, 4.5 Singles
5,1003,56, 4.5 Singles
我的问题是我仅从当前登录的用户#56开始,而不是div_id。
我需要有关“选择查询”的帮助,这将为我提供帮助:
Peter Pumpkin, 2137893434, pete@gmail.com
Jeremy Smith, 2138983465, jeremy@gmail.com
仅使用wp_player.id
我已经尝试过了:
SELECT p.player, p.cell, p.email
FROM wp_div d
INNER JOIN wp_play p ON p.id = d.player_id
WHERE d.player_id = $user_id
只给我一行信息
SELECT p.player, p.cell, p.email
FROM wp_div d
INNER JOIN wp_play p ON p.id = d.player_id
WHERE d.player_id = 54
我发现我是否使用此代码:
SELECT UPPER(`div_id`), `id`
FROM `wp_div`
WHERE `player_id` = '54'
我可以获得wp_div.div_id
,但是我不知道如何使用此输出来运行下一个查询以获取所需的输出:
Peter Pumpkin, 2137893434, pete@gmail.com
Jeremy Smith, 2138983465, jeremy@gmail.com
我的预期结果应该是使用用户的ID,我可以获得他所在部门中所有玩家的姓名,手机和电子邮件地址。
答案 0 :(得分:2)
您需要wp_divisions
之间的自联接。一种是获取杰里米(Jeremy)的行,另一种是将所有其他行放在相同的分区中。
SELECT p.player, p.cell, p.email
FROM wp_players AS p
JOIN wp_divisions AS d1 ON d1.player_id = p.id
JOIN wp_divisions AS d2 ON d1.div_id = d2.div_id
WHERE d2.player_id = 56