如何使用嵌套的SELECT语句使用内部子句中的外部子句的值?例如:
SELECT cost AS c, quantity, (SELECT COUNT(1) FROM accounts WHERE cost = c)
FROM accounts
如上所述,可以在内部SELECT子句中引用c
吗?
答案 0 :(得分:2)
外表的别名(例如FROM accounts AS a
)。然后,您只需在内部子查询中执行a.cost
。
EDIT。话虽这么说,有一种更好的方法来编写这个查询而不需要每行的子查询:
SELECT a.cost, a.quantity, COUNT(b.id) AS count
FROM accounts AS a LEFT JOIN accounts AS b ON b.cost = a.cost