如何在MySQL select语句的其他区域引用派生值?

时间:2012-09-05 07:16:47

标签: php mysql sql phpmyadmin mysqli

我正在尝试计算一个特殊分数。 '总计'并且正确的' (或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;

在这里,我试图为' total'创建一个别名。子查询返回的值,并在计算中用于评分。链接引用在子查询中工作,但总引用在第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。如果我尝试了左连接,则会抛出一般语法错误。

你能给我一个解决方案,并阐明其他尝试不起作用的原因吗?

1 个答案:

答案 0 :(得分: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;