每个派生表必须具有自己的别名

时间:2016-02-08 15:25:00

标签: mysql

这是我的MySQL语法:

SELECT f1.id
FROM
  (SELECT f1.id,
          count(*) AS c1
   FROM (friend AS f1
         JOIN friend AS f2 ON (f1.fid=f2.fid
                               AND f1.id!=f2.id
                               AND f2.id=12345
                               AND f1.id!=12345)))
WHERE c1>=
    (SELECT count(*)
     FROM friend AS f3
     WHERE f3.id=12345);

我似乎无法弄清问题的位置,我尝试对内部结果表进行别名,但它们似乎返回错误!我需要指导方针。

1 个答案:

答案 0 :(得分:2)

摆脱无关的括号并稍微格式化您的查询以使其看起来更整洁:

SELECT t.id 
FROM (SELECT f1.id,count(*) AS c1 
      FROM friend AS f1 
      JOIN friend AS f2
         ON  f1.fid=f2.fid AND 
             f1.id!=f2.id AND 
             f2.id=12345 AND 
             f1.id!=12345) AS t -- <-- Alias needed here!
WHERE c1>=(SELECT count(*) FROM friend as f3 WHERE f3.id=12345)

如果格式如上,那么您将意识到查询的派生表缺少别名。

此外,最外层查询选择的字段,即id,应使用派生表的别名(即t)作为前缀。