我可以使用派生属性在同一sql命令中定义另一个派生属性吗?

时间:2019-03-03 17:13:55

标签: mysql sql

我是sql的新手,想知道以下命令是否有效。

SELECT price, age, price * age AS PA, (PA-age)*age AS PS FROM P ;

如上所述,我可以使用上面定义的PA来定义PS吗?

2 个答案:

答案 0 :(得分:0)

您需要使用子查询或CTE:

    public class InvertedCircleView extends View {

    private Paint mPaint;
    private float mCanvasCenterX;

    private float mCenterCircleWidth, mCenterCircleHeight;


    public InvertedCircleView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

     [...]
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawPaint(mPaint);

        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

        mCenterCircleWidth = canvas.getWidth();        
        mCenterCircleHeight = canvas.getHeight();        

        mCanvasCenterX = canvas.getWidth() / 2;

        canvas.drawOval(mCanvasCenterX - (mCenterCircleWidth / 2),
                -mCenterCircleHeight,
                mCanvasCenterX + (mCenterCircleWidth / 2),
                mCenterCircleHeight,
                mPaint);
    }
 }

这是SQL限制,而不是MySQL限制。

答案 1 :(得分:0)

  

我可以使用上面定义的PA来定义PS吗?

不。 SELECT子句中定义的别名不能用于在该SELECT子句中构成另一列。 SELECT子句的表达式必须引用其他地方已经定义的术语。

幸运的是,该“其他位置”可以是另一个结果集,例如子查询。假设您的p表具有主键,也许是id字段:

SELECT
    p.price AS price,
    p.age AS age,
    pa.price_age AS price_age,
    ((pa.price_age - p.age) * p.age) AS price_schmurt
FROM p
    LEFT JOIN (
        SELECT
            p.id AS id,
            (p.price * p.age) AS price_age
        FROM p
        ) AS pa
        ON pa.id = p.id