使用SUM(某物)AS时字段列表中的未知列

时间:2017-05-30 12:44:01

标签: mysql sql

我使用以下查询从表中获取2列的总和

SELECT a.user, b.user, SUM(a.post = b.post) AS common_p_count,
SUM(a.option = b.option) AS common_r_count,
(common_p_count+common_r_count)
FROM response a, response b
WHERE a.user = '1' AND b.user != '1' group by b.user

但我得到未知列common_p_count

如何在此查询中使用common_p_count和common_r_count来排序结果?

谢谢

1 个答案:

答案 0 :(得分:2)

您无法选择已在SELECT子句中的同一级别定义的列。如果要重用表达式,则必须使用派生表:

SELECT x.*, (common_p_count+common_r_count)
FROM (
  SELECT 
    a.user AS a_user, 
    b.user AS b_user, 
    SUM(a.post = b.post) AS common_p_count,
    SUM(a.option = b.option) AS common_r_count
  FROM response a, response b
  WHERE a.user = '1' AND b.user != '1' group by b.user
) x

或者,当然,您只需重复以下表达式:

SELECT 
  a.user AS a_user, 
  b.user AS b_user, 
  SUM(a.post = b.post) AS common_p_count,
  SUM(a.option = b.option) AS common_r_count,
  (SUM(a.post = b.post) + SUM(a.option = b.option))
FROM response a, response b
WHERE a.user = '1' AND b.user != '1' group by b.user

如果您只是想通过该表达式进行排序,那么这可能没有任何技巧(但您仍然无法在查询的同一级别上SELECT表达式)

SELECT 
  a.user AS a_user, 
  b.user AS b_user, 
  SUM(a.post = b.post) AS common_p_count,
  SUM(a.option = b.option) AS common_r_count
FROM response a, response b
WHERE a.user = '1' AND b.user != '1' group by b.user
ORDER BY common_p_count + common_r_count

The reason for this is explained in this blog article here

侧面说明

除了上述解释之外,我当然不认为您的查询是正确的。由于您只按b.user进行分组,因此我会得到a.user的随机值,而且您的总和可能不正确,而且我认为您会得到偶然的笛卡尔积。但这是另一个问题的话题。