SELECT nodes.*, (SELECT (COUNT(*) FROM attachments
WHERE attachments.nodeid = nodes.id) AS attachmentcount
FROM nodes
WHERE attachmentcount > 0;
您将得到一个错误“未知列‘ attachmentcount’in WHERE 子句”。
解决方案实际上相当简单——只需将别名替换为生成别名的语句,例如:
SELECT nodes.*, (SELECT (COUNT(*) FROM attachments
WHERE attachments.nodeid = nodes.id) AS attachmentcount
FROM nodes
WHERE (SELECT (COUNT(*) FROM attachments WHERE attachments.nodeid = nodes.id) > 0;
SELECT u_name AS user_name ,
(SELECT last_name FROM users2 WHERE id=users.id) as user_last_name
FROM users WHERE u_name = "john" HAVING user_last_name ='smith'