我正在尝试将子查询生成的两个虚拟字段操作到一个新字段中,但是MySQL告诉我“GP”是一个未知列,但它已经被声明了。请看一下我的问题:
SELECT *,
(SELECT COUNT(id_gol) FROM tb_gol as gol
INNER JOIN tb_jogo as jg ON(gol.fk_id_jogo = jg.id_jogo)
WHERE gol.ic_excluido != '*' AND gol.fk_id_equipe = e.id_equipe AND jg.fk_id_campeonato = g.fk_id_campeonato) as 'GP',
(SELECT COUNT(id_gol) FROM tb_gol as gol
INNER JOIN tb_jogo as jg ON(gol.fk_id_jogo = jg.id_jogo)
WHERE gol.ic_excluido != '*' AND gol.fk_id_equipe != e.id_equipe AND (jg.fk_id_equipe1 = e.id_equipe OR jg.fk_id_equipe2 = e.id_equipe) AND jg.fk_id_campeonato = g.fk_id_campeonato) as 'GC',
(SELECT COUNT(id_wo) as WOs FROM tb_wo as w INNER JOIN tb_jogo as j ON (w.fk_id_jogo = j.id_jogo) WHERE w.fk_id_equipe = e.id_equipe AND j.fk_id_campeonato = g.fk_id_campeonato) as 'WO',
(GP+(GC*-1)) as 'SALDO'
FROM tb_equipe as e
INNER JOIN tb_gruposEquipes as ge ON (e.id_equipe = ge.fk_id_equipe)
INNER JOIN tb_grupos as g ON (g.id_grupo = ge.fk_id_grupo)
WHERE g.fk_id_campeonato = 23
ORDER BY WO ASC
如您所见,“SALDO”将是“GP-GC”的结果。但MySQL无法识别这些列
我该如何解决这个问题?
解
非常感谢你的帮助,伙计们,但我发现了问题。 无法通过减去GP的GC来创建“SALDO”,因为在运行期间“GP”和“GC”不存在。
因此,当您需要在运行时期间操作虚拟字段时,您将不得不重复生成虚拟字段的代码。
然后,如果你有这个选择:
SELECT *, (field1+1) as 'GP', (field2+1) as 'GC', (GP+GC) as 'SALDO' FROM (...)
您需要将其替换为:
SELECT *, (field1+1) as 'GP', (field2+1) as 'GC', ((field1+1)+(field2+1)) as 'SALDO' FROM (...)
答案 0 :(得分:1)
将内容推送到内部查询
SELECT core.*,
(GP+(GC*-1)) as 'SALDO'
from (
(SELECT COUNT(id_gol) FROM tb_gol as gol
INNER JOIN tb_jogo as jg ON(gol.fk_id_jogo = jg.id_jogo)
WHERE gol.ic_excluido != '*' AND gol.fk_id_equipe = e.id_equipe AND jg.fk_id_campeonato = g.fk_id_campeonato) as 'GP',
(SELECT COUNT(id_gol) FROM tb_gol as gol
INNER JOIN tb_jogo as jg ON(gol.fk_id_jogo = jg.id_jogo)
WHERE gol.ic_excluido != '*' AND gol.fk_id_equipe != e.id_equipe AND (jg.fk_id_equipe1 = e.id_equipe OR jg.fk_id_equipe2 = e.id_equipe) AND jg.fk_id_campeonato = g.fk_id_campeonato) as 'GC',
(SELECT COUNT(id_wo) as WOs FROM tb_wo as w INNER JOIN tb_jogo as j ON (w.fk_id_jogo = j.id_jogo) WHERE w.fk_id_equipe = e.id_equipe AND j.fk_id_campeonato = g.fk_id_campeonato) as 'WO' )
FROM tb_equipe as e
) as core
INNER JOIN tb_gruposEquipes as ge ON (core.id_equipe = ge.fk_id_equipe)
INNER JOIN tb_grupos as g ON (g.id_grupo = ge.fk_id_grupo)
WHERE g.fk_id_campeonato = 23
ORDER BY WO ASC