在mysql中使用虚拟列

时间:2013-03-04 03:09:10

标签: mysql sql database select

我有如下的mysql查询:

SELECT
  company_name,
  SUM(purchase_qty * num_of_certificate) AS total_purchase_qty,
  total_sold_qty,
  (total_purchase_qty - total_sold_qty) AS rem_qty
FROM tbl_company
  JOIN tbl_share_purchase
ON purchase_company_id = tbl_company.id
  JOIN (SELECT
      sold_company_id,
      SUM(sold_qty)   AS total_sold_qty
    FROM tbl_share_sales
    GROUP BY sold_company_id) s
ON s.sold_company_id = tbl_company.id
GROUP BY purchase_company_id

是否可以使用(total_purchase_qty - total_sold_qty)AS rem_qty 来获取剩余数量?

1 个答案:

答案 0 :(得分:4)

如果将它包装在子查询上,则可以这样做,但如果它在同一级别定义,则无法使用别名进行计算,

SELECT  company_name,
        SUM(purchase_qty * num_of_certificate) AS total_purchase_qty,
        total_sold_qty,
        (SUM(purchase_qty * num_of_certificate) - total_sold_qty) AS rem_qty
FROM    tbl_company
        JOIN tbl_share_purchase
            ON purchase_company_id = tbl_company.id
        JOIN 
        (
            SELECT  sold_company_id,
                    SUM(sold_qty)   AS total_sold_qty
            FROM    tbl_share_sales
            GROUP   BY sold_company_id
        ) s ON s.sold_company_id = tbl_company.id
GROUP   BY purchase_company_id

这里使用子查询,

SELECT  company_name,
        total_purchase_qty,
        total_sold_qty,
        (total_purchase_qty - total_sold_qty) AS rem_qty
FROM
(
    SELECT  company_name,
            SUM(purchase_qty * num_of_certificate) AS total_purchase_qty,
            total_sold_qty
    FROM    tbl_company
            JOIN tbl_share_purchase
                ON purchase_company_id = tbl_company.id
            JOIN 
            (
                SELECT  sold_company_id,
                        SUM(sold_qty)   AS total_sold_qty
                FROM    tbl_share_sales
                GROUP   BY sold_company_id
            ) s ON s.sold_company_id = tbl_company.id
    GROUP   BY purchase_company_id
)