我有一个查询来提取给定发布商ID的总数。我想将它用作子查询,以便我可以迭代所有发布者ID。
我对给定ID的查询是:
SELECT SUM( d.our_cost )
FROM articles a
CROSS JOIN domains d ON a.domain_id = d.id
AND d.publisher_id = '1094'
我想为发布商p表中的所有ID提取此数字,其中d.publisher_id = p.id
到目前为止,我已经尝试了以下内容无济于事:
SELECT p.id, p.contact_name, p.contact_email,
(SELECT SUM(d.our_cost)
FROM articles a
CROSS JOIN domains d ON a.domain_id = d.id and d.publisher_id = p.id) total
FROM publishers p
我得到的具体错误是:'on clause'
中的未知列'p.id'答案 0 :(得分:1)
我认为你应该修改你的查询并将子查询放在from子句中,如下所示:
SELECT p.id, p.contact_name, p.contact_email, total.total_cost
FROM
(
SELECT SUM(d.our_cost) as total_cost, d.publisher_id
FROM articles a CROSS JOIN domains d ON a.domain_id = d.id ) total
JOIN publishers p on total.publisher_id = p.id
答案 1 :(得分:0)
我假设您的语法错误,请尝试:
SELECT p.id, p.contact_name, p.contact_email, SUM(d.our_cost) as total
FROM articles a
CROSS JOIN domains d ON a.domain_id = d.id
JOIN publishers p ON d.publisher_id = p.id
答案 2 :(得分:0)
似乎是一个小组,而不是
此外,您似乎根本不需要文章表(除非您有其他业务规则)
SELECT p.id, p.contact_name, p.contact_email, IFNULL(SUM(d.our_cost),0) AS total
FROM publishers p
LEFT JOIN domains d ON d.publisher_id = p.id
GROUP BY p.id