在多级子查询MySQL

时间:2016-12-28 08:07:23

标签: mysql database

这是我的查询

SELECT *
FROM personal_store_application a, personal_store_application_lang b, (

  SELECT SUM( total ) total
  FROM (

     SELECT COUNT( NPID ) total
     FROM actnews
     WHERE `NPID` = a.PID
     UNION ALL SELECT COUNT( NPID ) total
     FROM logistics
     WHERE `NPID` = a.PID
  ) AS s
) AS x
WHERE a.Sn = b.Sn
AND b.Lang = 'zh-tw'
AND Application != 'S'
ORDER BY a.C_TIME DESC 

此查询在第二级Unknown column 'a.PID' in 'where clause'中断 我无法在二级子查询中访问别名a。怎么做到这一点?如果我将a.PID更改为静态PID,则查询可以正常工作。

提前致谢:)

2 个答案:

答案 0 :(得分:0)

当您执行子查询时,最内层查询首先执行,在您的情况下SELECT COUNT( NPID ) total FROM actnews WHERE NPID = a.PID UNION ALL SELECT COUNT( NPID ) total FROM logistics WHERE NPID = a.PID

,它不知道什么是a.,因为它在外部查询中声明,因此错误。

答案 1 :(得分:0)

也许你可以使用左连接

 SELECT COUNT( NPID ) total
 FROM actnews
 LEFT JOIN personal_store_application ON `NPID` = personal_store_application.PID