MySQL计为{name}和WHERE {name} = X,未知列

时间:2018-03-23 17:06:54

标签: mysql sql mysqli

我正在尝试根据count()上指定的名称过滤结果,并得到:

Unknown column 'total_submissions' in 'where clause'

SELECT SQL_CALC_FOUND_ROWS patient.*,count(patient_data.id) as total_submissions 
FROM patient 
LEFT JOIN patient_data ON (patient_data.patient_id = patient.id AND patient_data.date_finished IS NOT NULL) 
WHERE patient.doc_id = 2 AND total_submissions = 5 
GROUP BY patient.id 
ORDER BY patient.id DESC 
LIMIT 0,40

经过更多研究后,我确实发现无法在WHERE中使用列别名,但我不确定如何执行此查询。我认为这是可能的,但我怎样才能根据查询的count()计算过滤结果?

2 个答案:

答案 0 :(得分:2)

>>> merged_list=[None]*3 >>> print merged_list [None, None, None] 是列别名聚合函数的结果。您需要在total_submissions子句中进行检查:

having

注意:

  • 表别名使查询更易于编写和阅读。
  • SELECT SQL_CALC_FOUND_ROWS p.*, count(pd.id) as total_submissions FROM patient p LEFT JOIN patient_data pd ON pd.patient_id = p.id AND pd.date_finished IS NOT NULL WHERE p.doc_id = 2 GROUP BY p.id HAVING total_submissions = 5 ORDER BY p.id DESC LIMIT 0, 40; 上的条件仍应在doc_id条款中。

答案 1 :(得分:1)

你不能在where子句中使用列别名,因为在评估where子句时,sql评估中的优先级不允许db引擎知道别名

首先评估FROM clase然后是WHERE子句和SELECT cluase之后.. 在您的情况下,您有一个与yu别名相关的聚合函数,这只能在执行group by后进行评估,在查询过程结束时进行实际操作 因此,有一个基于HAVING的适当过滤器可以处理受到攻击的查询的结果

  SELECT SQL_CALC_FOUND_ROWS patient.*, count(patient_data.id) as total_submissions 
  FROM patient 
  LEFT JOIN patient_data ON (patient_data.patient_id = patient.id AND patient_data.date_finished IS NOT NULL) 
  WHERE patient.doc_id = 2
  GROUP BY patient.id 
  HAVING  total_submissions = 0 
  ORDER BY patient.id DESC 
LIMIT 0,40