前言:在使用mysql做count计数多表查询或子查询的时候犯了一个低级的错误:

1248 – Every derived table must have its own alias(每个派生表都必须有自己的别名)

报错sql:

SELECT count(*) FROM ( SELECT t.id id, t1.id t1_id, t2.id t2_id FROM t_school t LEFT JOIN t_teacher t1 ON t.teacherid = t1.id LEFT JOIN t_user t2 ON t.userid = t2.id WHERE 1 = 1 ) 

执行这条语句就会报错:Every derived table must have its own alias。

简单的SQL构成是:select 字段名 from 表名,上面子查询里面查出来的是数据,没有被当成一个表,使用我们只需要在SQL后面加上AS 表名 给他一个表的名字即可

修改过后的SQL:

SELECT count(*) FROM ( SELECT t.id id, t1.id t1_id, t2.id t2_id FROM t_school t LEFT JOIN t_teacher t1 ON t.teacherid = t1.id LEFT JOIN t_user t2 ON t.userid = t2.id WHERE 1 = 1 ) AS a

加上表名之后即可解决报错了。

发表评论

电子邮件地址不会被公开。 必填项已用*标注