曲棍球APP。必须查询表2中的所有行并显示玩家NAME而不是播放器ID
*注意:新的堆栈溢出抱歉格式
表1:球员
╔═════════════════════╗
║ id | fname | lname ║
╠═════════════════════╣
║ 1 | Jason | McFee ║
║ 2 | John | Smith ║
║ 3 | Jack | Doe ║
╚═════════════════════╝
表2:events_goals
╔═════════════════════════╗
║ id g_id a1_id a2_id ║
╠═════════════════════════╣
║ 1 1 2 3 ║
║ 2 3 1 2 ║
║ 3 2 1 3 ║
╚═════════════════════════╝
我想要做的是从events_goals获取每一行并使用匹配的玩家名称返回
我想要成就什么:玩家名字被执行了,我不需要名字旁边的(#)我只是把它放在那里引用玩家ID
表3
╔════════════════════════════════════════════════╗
║ id goal assist1 assist2 ║
╠════════════════════════════════════════════════╣
║ 1 Jason McFee(1) John SMith(2) Jack Doe(3) ║
║ 2 Jack Doe(3) Jason McFee(1) John Smith(2) ║
║ 3 John Smith(2) Jason McFee(1) Jack Doe (3) ║
╚════════════════════════════════════════════════╝
我做了什么
我尝试了很多不同的查询,这是迄今为止最好的查询
SELECT players.fname AS GFN,
players.lname AS GLN
FROM events_goals
LEFT JOIN players
ON events_goals.g_id = players.playerid
返回:
╔═══════════════╗
║ GFN GLN ║
╠═══════════════╣
║ Jason McFee ║
║ Jack Doe ║
║ John Smith ║
╚═══════════════╝
我可以为Assists1和Assists 2运行相同的代码,但是我无法成功地将所有3个SELECT查询加入到一起,理想情况下我想将第一个和最后一个名称列加入到1个单元格中,但我可以不用它,主要是将所有ID转换为名称
答案 0 :(得分:2)
JOIN
表players
在表event_goals
上三次,因为有三列依赖于players.id
。
SELECT a.ID,
CONCAT_WS(' ', b.fname, b.lname) goal,
CONCAT_WS(' ', c.fname, c.lname) assist1,
CONCAT_WS(' ', d.fname, d.lname) assist2
FROM event_goals a
INNER JOIN players b
ON a.g_id = b.id
INNER JOIN players c
ON a.a1_id = c.id
INNER JOIN players d
ON a.a2_id = d.id
ORDER BY a.id