计算出的mysql变量不会显示在PHP结果集

时间:2017-09-02 04:53:43

标签: php mysql

当我在Sequel Pro中运行以下查询时,我会获得所有列的结果

select distinct
@company_id := a.company_id as company,
@current_date := max(stock_date) as currentdate, 
@other_date := date_sub(@current_date, interval 0 day) as other_date, 
@shares_bought := (select sum(volume) from my_portfolio where company_id=@company_id and posted_by = '5977479698B58' and trans_type='BUY') as shares_bought, 
@shares_sold := (select IF(sum(volume) IS NULL, 0, sum(volume)) from my_portfolio where company_id=@company_id and posted_by = '5977479698B58' and trans_type='SELL') as shares_sold, 
@shares_held := (@shares_bought-@shares_sold) as shares_held, 
@current_price := (select close from stock_prices where company_id=@company_id and stock_date <= @other_date order by stock_date desc limit 1) as current_price, 
(@current_price*@shares_held) as market_value 
from my_portfolio a 
inner join stock_prices b on a.company_id = b.company_id 
group by company

但是,我的PHP var_dump()显示实际具有值的某些列的空值。

Image: var_dump from PHP

Image: results of the same query from Sequel Pro

1 个答案:

答案 0 :(得分:0)

如果other_date始终与currentdate相同,请尝试以下内容:

SELECT company, currentdate, currentdate AS other_date, shares_bought, shares_sold,
       shares_held, current_price, current_price * shares_held AS market_value
FROM ( SELECT company, currentdate, currentdate AS other date, shares_bought, shares_sold,
              shares_bought - shares_sold AS shares_held, 
              ( SELECT close FROM stock_prices WHERE company_id = q.company_id
                   AND stock_date <= currentdate ORDER BY stock_date DESC
                LIMIT 1 ) AS current_price
       FROM ( SELECT a.company_id AS company, MAX(stock_date) AS currentdate,
                     COALESCE( SUM( b.volume ), 0 ) AS shares_bought,
                     COALESCE( SUM( s.volume ), 0 ) AS shares_sold
              FROM stock_prices a
              JOIN my_portfolio b ON b.company_id = a.company_id AND b.trans_type = 'BUY'
                                 AND b.posted_by = '5977479698B58'
              JOIN my_portfolio s ON s.company_id = a.company_id AND s.trans_type = 'SELL'
                                 AND s.posted_by = '5977479698B58'
              GROUP BY a.company_id
            ) q
     ) w

我很想使用CTE(WITH子句),但它只适用于MySQL 8 ....