我有两张桌子;一个包含产品统计信息,另一个包含其他统计信息
StatsHourly:
id
product_id (can be multiple)
amount
cost
time
StatsValues:
id
product_id (can be multiple)
value (double)
我需要加入这两个表并在结果中得到类似的结果:
product_id
sum (amount)
sum (cost)
sum (value)
我试图这样做:
"SELECT
SUM(s.amount) as amount,
SUM(s.cost) as cost
FROM StatsHourly s
LEFT JOIN (
SELECT
COALESCE(SUM(value), 0) as value
FROM StatsValues
GROUP BY product_id
) value v ON v.product_id = s.product_id
WHERE 1
AND s.product_id = :product_id";
这不起作用。有人能告诉我正确的方法吗?
答案 0 :(得分:1)
as cost
之后还有一个额外的逗号:
SUM(s.cost) as cost, <-- here
您还为子查询使用了2个别名,您应该从那里删除值:
) value v
您不使用子查询中的任何输出。
子查询中不需要Coalesce()。
答案 1 :(得分:-1)
这有效(经过测试):
SELECT
s.product_id as product_id,
s.amount_s as amount,
s.cost_s as cost,
v.value_v as value
FROM
(SELECT
product_id,
SUM(amount) as amount_s,
SUM(cost) as cost_s
FROM StatsHourly
GROUP BY product_id) as s
LEFT JOIN
(SELECT
product_id,
SUM(value) as value_v
FROM StatsValues
GROUP BY product_id) as v
ON v.product_id = s.product_id;
WHERE s.product_id = 'product_id';
重点是:
此致