0

我正在尝试计算一个特殊分数。'total' 和 'correct' (or order) 需要不同的查询才能获得,并且总需要在两个地方使用。这导致了使用别名的问题。在这种情况下,重复子查询的性能和可读性太高。我尝试了两种不同的方法来让它工作:

SELECT rankings.id as link, (
  SELECT COUNT(*) as total FROM rankings
  INNER JOIN ranking_data ON ranking_id = rankings.id AND `type` = 'pre_reference'
  WHERE case_id = 15 AND rankings.id = link
) as total,
ROUND(((total - `order`) / total) * 100, 2) AS score FROM rankings
INNER JOIN ranking_data ON ranking_id = rankings.id AND opinion_id = 124 AND `type` = 'pre_reference'
WHERE case_id = 15 AND user_id != 3;

在这里,我尝试为子查询返回的“总”值创建一个别名,并将其用于评分计算。链接引用在子查询中有效,但总引用在第 6 行失败。

SELECT ROUND(((total - `order`) / total) * 100, 2) AS score FROM rankings
INNER JOIN ranking_data ON ranking_id = rankings.id AND opinion_id = 124 AND `type` = 'pre_reference'
INNER JOIN (
  SELECT COUNT(*) as total FROM rankings
  INNER JOIN ranking_data ON ranking_id = rankings.id AND `type` = 'pre_reference'
  WHERE case_id = 15
) AS total_table ON total_table.id = rankings.id
WHERE case_id = 15 AND user_id != 3;

在这里,我尝试通过左连接派生表来使总和可用于列列表区域进行评分。MySQL 在第 7 行告诉我找不到 total_table.id。如果我尝试左连接,它会抛出一般语法错误。

你能给我一个解决方案,并阐明为什么其他尝试没有奏效吗?

4

1 回答 1

1

在第二个查询中,id未明确包含在内total_table联视图中选择的列集中;您可能还需要分组id。尝试将查询更改为:

SELECT ROUND(((total - `order`) / total) * 100, 2) AS score 
FROM rankings
INNER JOIN ranking_data 
ON ranking_id = rankings.id AND opinion_id = 124 AND `type` = 'pre_reference'
INNER JOIN 
( SELECT rankings.id, COUNT(*) as total FROM rankings
  INNER JOIN ranking_data 
  ON ranking_id = rankings.id AND `type` = 'pre_reference'
  WHERE case_id = 15
  GROUP BY rankings.id
) AS total_table 
ON total_table.id = rankings.id
WHERE case_id = 15 AND user_id != 3;
于 2012-09-05T07:26:17.230 回答