相关表格和尝试的解决方案已在帖子底部列出。目标和问题将在下面立即描述。
目标
此查询的目标是在下面构建PHP对象数组(返回的行)。这是为用户过滤的每个货币对进行的每笔交易的时间戳记录。除了cumulative_quantity
值
'BTC-USD' => array(
array(
'timestamp' => (int),
'price' => (float),
'price_usd' => (float),
'buy_sell' => (bool),
'quantity' => (float),
'total_value' => (float),
'total_value_usd' => (float),
'cumulative_quantity' => (float),
'cumulative_quantity_base' => (float)
)
)
问题
计算pf_items
中每个用户行的累积数量还需要检查buy_sell
字段是0(卖出)还是1(买入)并相应地加/减。
由于cumulative_quantity_base
要求将BTC-USD和(例如)BTC-EUR的quantity
值合并到一个简单的BTC对象数组下,因此它变得稍微复杂一些。例如,如果pf_items
中与BTC-USD有关的行(base_currency
和quote_currency
)的购买量为5,而另一行与BTC-EUR相关的购买量为7,需要找到以下两行的BTC累积值:12。
pf_currencies
CREATE TABLE `pf_currencies` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`symbol` varchar(255) NOT NULL
);
pf_currencies_history
CREATE TABLE `pf_currencies_history` (
`id` int(11) NOT NULL,
`base_currency` int(11) NOT NULL,
`quote_currency` int(11) NOT NULL,
`price` float NOT NULL,
`date_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);
pf_portfolios
CREATE TABLE `pf_portfolios` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date_added` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
pf_items
CREATE TABLE `pf_items` (
`id` int(11),
`portfolio_id` int(11),
`action_date` date,
`price` float,
`price_usd` float,
`buy_sell` tinyint(1),
`quantity` float,
`base_currency` int(11),
`quote_currency` int(11),
`date_added` datetime
)
我的查询
此查询可实现除所述的cumulative_quantity
和cumulative_quantity_base
之外的其他功能。
SELECT (SELECT
symbol
FROM pf_currencies
WHERE a.base_currency = id)
AS base_currency,
(SELECT
symbol
FROM pf_currencies
WHERE a.quote_currency = id)
AS quote_currency,
a.price,
UNIX_TIMESTAMP(a.date_time) AS unix_time
FROM pf_currencies_history a
INNER JOIN pf_items i
ON i.portfolio_id = (SELECT
id
FROM pf_portfolios
WHERE user_id = ".$userId.")
AND a.base_currency = i.base_currency
AND a.quote_currency = i.quote_currency
ORDER BY unix_time DESC