mysql where 子句子查询无法识别外部查询中的 table 别名

mysql where clause subquery does not recgnize table alias in outer query

以下查询:

SELECT wp_users.* 
FROM wp_users 
INNER JOIN  wp_usermeta AS mtct  ON ( wp_users.ID = mtct.user_id )  
WHERE not exists (select * from mtct where mtct.meta_key='City')  

给我

Error Code 1146: Table '.mtct' doesn't exist.

我已经搜索过类似的问题,但我仍然看不出我做错了什么。我在 centos 6.4 上使用 mysql 5.6.21。

您不能在 FROM 子句中使用 table 别名,您必须在那里使用真实的 table 名称。

SELECT wp_users.* 
FROM wp_users 
INNER JOIN  wp_usermeta AS mtct  ON ( wp_users.ID = mtct.user_id )  
WHERE not exists (select * 
                  from wp_usermeta AS mtct1
                  where mtct1.meta_key='City') 

这将修复错误,但我不确定它是否会给您想要的结果。子查询可能需要与主查询中的 table 之一相关联。或许是这样:

SELECT wp_users.* 
FROM wp_users 
INNER JOIN  wp_usermeta AS mtct  ON ( wp_users.ID = mtct.user_id )  
WHERE not exists (select * 
                  from wp_usermeta AS mtct1
                  where mtct1.meta_key='City'
                    and mtct1.user_id = wp_users.ID) 

但是,似乎没有任何理由加入 wp_usermeta,因为您没有从 table 中选择任何内容。这可能只是:

SELECT * 
FROM wp_users 
WHERE not exists (select * 
                  from wp_usermeta AS mtct1
                  where mtct1.meta_key='City'
                    and mtct1.user_id = wp_users.ID) 

这将 return 所有在 wp_usermeta 中没有 City 的用户。

@Barmar 解释了原因,您不能在 from 子句中使用别名,因为 from 子句必须具有 table 名称,下面的查询可以满足您的目的,并且在体积庞大的情况下可能会更快tables.

SELECT wu.* 
FROM wp_users wu 
LEFT JOIN  wp_usermeta AS mtct  ON wu.ID = mtct.user_id AND mtct.meta_key='City'
WHERE mtct.id IS NULL;