开发者

How to use column name from an outer clause in an inner clause?

How can I use the value from an outer clause inside an inner clause using nested SELECT statements? Eg:

SELECT cost AS c,开发者_如何学编程 quantity, (SELECT COUNT(1) FROM accounts WHERE cost = c) 
FROM accounts

Can c be referenced in the inner SELECT clause as attempted above?


Alias the outer table (eg. FROM accounts AS a). Then you can simply do a.cost in the inner subquery.

EDIT. That being said, there's a better way to write this query without a sub-query for each row:

SELECT a.cost, a.quantity, COUNT(b.id) AS count
FROM accounts AS a LEFT JOIN accounts AS b ON b.cost = a.cost
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜