MySQL问题记录之select后面子查询别名失效问题

今天写SQL语句的时候碰到一个问题,select后面子查询别名失效问题.
这是我一开始写的一个代码:

SELECT
	sum( IFNULL( money, 0 ) ) money,
	salesman_id 
FROM
	(
	SELECT
		salesman_id,
		(
		SELECT
			r.money 
		FROM
			( SELECT order_id, sum( money ) money FROM b_order_receivables WHERE NAME != '保障金' AND state = 2 GROUP BY order_id ) r 
		WHERE
			r.order_id = o.id 
		)* o.commission / 100 AS money 
	FROM
		b_order o 
	WHERE
		deleted = 0 
		AND salesman_id IS NOT NULL 
		AND money IS NOT NULL 
	) s 
GROUP BY
	s.salesman_id

然后执行的时候直接报错了;
MySQL问题记录之select后面子查询别名失效问题_第1张图片
说where子句”中的“money”列未知也就是别名没有被识别出来;
这里当时我就很奇怪这个代码写得没毛病呀怎么就别名出不来了,然后我又想了一会MYSQL如何定义别名的

字段 AS “别名” (其中AS可以省略不写, 别名用引号引起来,引号可以是双引号,也可以是单引号,建议大家使用双引号)

所以我又加上双引号试了一下.

-- 查询业务员下提成
SELECT
	sum( IFNULL( money, 0 ) ) money,
	salesman_id 
FROM
	(
	SELECT
		salesman_id,
		(
		SELECT
			r.money 
		FROM
			( SELECT order_id, sum( money ) money FROM b_order_receivables WHERE NAME != '保障金' AND state = 2 GROUP BY order_id ) r 
		WHERE
			r.order_id = o.id 
		)* o.commission / 100 AS "money" 
	FROM
		b_order o 
	WHERE
		deleted = 0 
		AND salesman_id IS NOT NULL 
		AND "money" IS NOT NULL 
	) s 
GROUP BY
	s.salesman_id

嗯完美.
MySQL问题记录之select后面子查询别名失效问题_第2张图片
这里这个问题我总结了一下,归根结底出现就是因为我自己代码平时为了省事,导致代码不规范;

你可能感兴趣的:(MySql,sql,mysql)