我一直在寻找这个,我总是得到改变做事方式的答案,但没有解决一般问题,即:在嵌套 SELECT 中引用主查询变量。
我需要它是一个嵌套查询,因为数据结构非常复杂。让我们看看我需要做的例子:
SET @teamg_id := 0;
SELECT
@teamg_id := player.team_id,
player.team_id AS player_team,
event.local_team_id AS local_team,
event.visitor_team_id AS visitor_team,
action.unique_id AS action_id,
action.player_id AS player_id,
player.name AS player_name,
playerindex.rank AS player_pos,
playerindex.ses_var_nest AS ses_var_nest
FROM
er_players player,
er_events event,
er_actions action
LEFT JOIN
(SELECT
unique_id, team_id, @pn:=@pn+1 AS rank, @teamg_id AS ses_var_nest
FROM
er_players, (SELECT @pn:=-1) p2
WHERE
team_id = @teamg_id
ORDER BY
dorsal ASC, id DESC) playerindex
ON
playerindex.unique_id = action.player_id
WHERE
action.unique_id = '1374572622'
AND player.unique_id = action.player_id
AND event.unique_id = (SELECT event_id
FROM er_analysis
WHERE unique_id = action.analysis_id)
如您所见,我需要返回该球员在他的球队中的“索引”,按照查询返回的顺序(排名值),但我需要将其计算为与球队相关,而不是整个玩家表。
为此,我需要在嵌套的 SELECT 中引用主查询值“player.team_id”——我尝试过但无法做到,所以我结束了使用会话变量。
我从这个查询中得到的是 @teamg_id 在主查询中很好地存储了值,但是当传递给嵌套查询时,它的值变成了 NULL:
@teamg_id | player_team | local_team | visitor_team | action_id | player_id | player_name | player_pos | ses_var_nest
1374570040 | 1374570040 | 1374570040 | 1374571827 | 1374572622 | 1374570146 | Player name | NULL | NULL
我的问题是如何在嵌套查询中使用会话变量(我认为它应该可以工作),或者如何在其中引用主查询值。
谢谢你的帮助!
编辑:这是 er_players 表的结构,它给我带来了问题。如果我说“给我'玩家 3' 的索引”,它应该给我 2 (0, 1, 2),因为这是他团队中的第三个玩家。
+------------+------------+----------+----------+--------+
| unique_id | team_id | name | position | dorsal |
+------------+------------+----------+----------+--------+
| 1374570066 | 1374570040 | Player 1 | Defense | 1 |
| 1374570034 | 1374570040 | Player 2 | Defense | 2 |
| 1374677119 | 1374571827 | Player 7 | Position | 7 |
| 1374570146 | 1374570040 | Player 3 | Attack | 5 |
+------------+------------+----------+----------+--------+
编辑 2(解决方案):由于 Kordirko 的回答和一些游戏,找到了解决方案。
SELECT
player.team_id AS player_team,
event.local_team_id AS local_team,
event.visitor_team_id AS visitor_team,
action.unique_id AS action_id,
action.player_id AS player_id,
player.name AS player_name,
playerindex.rank AS player_pos,
playerindex.ses_var_nest AS ses_var_nest
FROM
er_actions action
LEFT JOIN er_events event
ON event.unique_id = (SELECT event_id FROM er_analysis WHERE unique_id = action.analysis_id)
LEFT JOIN er_players player
ON player.unique_id = action.player_id
LEFT JOIN
(SELECT
unique_id, team_id, team_id AS ses_var_nest ,
case when team_id <> @lastteam
then (@pn:=-1)
end AS hander,
case when team_id <> @lastteam
then(@lastteam:=team_id)
end AS team_id_new,
@pn:=@pn+1 AS rank
FROM
er_players, (SELECT (@pn:=-1),(@lastteam:=0)) p2
ORDER BY
team_id, dorsal ASC, id DESC) playerindex
ON
playerindex.unique_id = action.player_id
AND playerindex.team_id = player.team_id /* new join condition */
WHERE
action.unique_id = '1374572622'
在 CASES 之后选择 @rank 使其不会两次为 0,并在选择之前重置 @rank。否则,它会变成0,而是变成每支球队的第二名球员。
希望有人能找到有帮助的这个问题。
再次感谢 Kordirko 的时间和回答。