这几乎看起来像是范围问题 - 子查询中的select语句无法识别表'候选':
SELECT
candidate.id AS id,
candidate.image AS image,
candidate.name AS name,
candidate.party AS party,
player.order AS player_order,
c_pcts.pct AS pct
FROM `candidate`
INNER JOIN players player ON player.candidate_id = candidate.id
INNER JOIN lineups lineup ON player.lineup_id = lineup.id
INNER JOIN (
SELECT
pct
FROM candidate_pcts p
INNER JOIN weekly_game game ON p.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
) WHERE p.candidate_id = candidate.id
) c_pcts
WHERE lineup.id = '31'
ORDER BY player.order ASC
在“where子句”中给出错误:“未知列'candidate.id'。”如果不是“FROM candidate_pcts p”,我就把
FROM candidate_pcts p, candidate c
然后它没有看到'p.weekly_game_id'......嗯?
似乎我需要以某种方式识别子查询的“候选”表,但我正在尝试的一切只会让我误入歧途。而且我已经尝试了很多东西:桌子的顺序,明确地识别它们我想到的任何地方,反叛。我应该注意到嵌套的子查询就像一个魅力。这又是:
SELECT
pct
FROM `candidate_pcts`
INNER JOIN weekly_game game ON candidate_pcts.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
) WHERE candidate_pcts.candidate_id = '5'
当然,在那里使用硬编码的id值。如果需要,我可以提供数据库结构,但这已经很久了。 'weekly_game'表只是每周每位候选人的一组分数,我们只想要最近一周的分数,因此是“ORDER BY date DESC LIMIT 1”条款。
非常感谢你的时间。
表:
candidate
: {id
,image
,name
,party
}
candidate_pcts
: {id
,candidate_id
,pct
,weekly_game_id
}
lineups
: {id
,date, user_id
}
players
: {id
,candidate_id
,lineup_id
,order
}
weekly_game
: {id
,date
}
答案 0 :(得分:0)
你基本上在问题的正确轨道上。本质上,嵌套的子选择不知道candidate.id
。你打破了查询,只看下有问题的子选择:
SELECT
pct
FROM candidate_pcts p
INNER JOIN weekly_game game ON p.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
) WHERE p.candidate_id = candidate.id
您可以看到除了where子句之外,candidate
表中的查询没有任何引用,因此这是一个未知列。
由于subselect实质上是在引用它的外部select之前进行的,因此subselect必须是一个独立的可执行查询。
答案 1 :(得分:0)
感谢所有人,尤其是迈克的出色解释。我所做的是重新构建了这样的查询:
SELECT
candidate.id AS id,
candidate.image AS image,
candidate.name AS name,
candidate.party AS party,
player.order AS player_order,
pcts.pct AS pct
FROM `candidate`
INNER JOIN players player ON player.candidate_id = candidate.id
INNER JOIN lineups lineup ON player.lineup_id = lineup.id
LEFT JOIN (
SELECT
p.candidate_id AS pct_id, pct AS pct
FROM candidate_pcts p
INNER JOIN weekly_game game ON p.weekly_game_id = (
SELECT id FROM weekly_game ORDER BY date DESC LIMIT 1
)
) pcts
ON pct_id = candidate.id
WHERE lineup.id = '$lineup_id'
ORDER BY player.order ASC