一、問題
在mysql中給字段起別名后,where子句中使用別名查詢出現問題
SELECT
s.sid AS 學號,
s.sname AS 姓名,
COUNT(sc.course_id
) AS 選課數,
SUM(IFNULL(sc.num
,0)) AS 總成績
FROM
student s
LEFT JOIN
score sc
ON
'學號'=sc.student_id
GROUP BY
'學號';
二、解決方案
別名分為兩類:
1、表的別名,比如FROM student s,s就是student的別名;
2、查詢結果中,對字段起別名,比如s.id as '學號',學號就是s.id的別名;
第二類別名,是建立在第一類別名的基礎上的。而where中,只能使用表的別名+屬性名(比如where s.id=1),而不能使用‘學號=1’。
SELECT ancestors,CONCAT(',',ancestors,',') AS 'wmtest' FROM `sys_company` WHERE CONCAT(',',ancestors,',') LIKE '%,28,%';
這里where 后面不能寫成 where 'wmtest' like '%,28,%';這樣就報錯了,不能識別'wmtest'這一列。