1

我已经发布了另一条这样的消息。但没有一个帮助。所以我做了更多的阅读,我有这段代码可以工作:

编辑新版本和新问题

SELECT i.*, o.organ_name, o.organ_logo, vtable.*
FROM heroku_056eb661631f253.op_ideas i
JOIN
(SELECT
    COUNT(v.agree) as agree,
    COUNT(v.disagree = 1 or null) as disagree,
    COUNT(v.obstain = 1 or null) as abstain
FROM op_idea_vote v
) AS vtable
LEFT JOIN op_organs o ON i.post_type = o.organs_id

op_idea_vote 表中只有 1 行,op_ideas 表中只有 3 行。但它给每一行每个 op_ideas 行的总数

编辑工作解决方案

感谢 WayneC,这是工作代码:

SELECT i.*, o.organ_name, o.organ_logo, vtable.*
FROM heroku_056eb661631f253.op_ideas i
JOIN
   (SELECT v.idea_Id,
    COUNT(v.agree = 1 or null) as agree,
    COUNT(v.disagree = 1 or null) as disagree,
    COUNT(v.obstain = 1 or null) as abstain
   FROM op_idea_vote v
   GROUP BY v.idea_id
   ) AS vtable ON vtable.idea_id = i.idea_id
LEFT JOIN op_organs o ON i.post_type = o.organs_id
WHERE idea_geo = 'International';
4

2 回答 2

2

试试这个

SELECT i.*, o.organ_name, o.organ_logo, vtable.*
FROM heroku_056eb661631f253.op_ideas i
JOIN
    (SELECT
        COUNT(v.agree) as agree,
        COUNT(v.disagree = 1 or null) as disagree,
        COUNT(v.obstain = 1 or null) as abstain
    FROM op_idea_vote v
    GROUP BY v.idea_id
    ) AS vtable ON vtable.idea_id = i.idea_id
LEFT JOIN op_organs o ON i.post_type = o.organs_id

下面的答案缺少分组依据和 vtable 的加入条件

于 2012-10-14T11:14:12.613 回答
1

这是您的原始查询

SELECT i.*, o.organ_name, o.organ_logo
FROM heroku_056eb661631f253.op_ideas i
JOIN
    (SELECT
        COUNT(v.agree) as agree,
        COUNT(v.disagree = 1 or null) as disagree,
        COUNT(v.obstain = 1 or null) as abstain
    FROM op_idea_vote v, op_ideas i
    WHERE v.idea_id = i.idea_id
    ) AS vtable
  LEFT JOIN op_organs o ON i.post_type = o.organs_id

vtable是一个伪装成您要加入的表的子查询 - 就获取要与查询结果一起返回的字段而言,它与加入普通表没有什么不同。您必须在主查询中选择要返回的字段,否则它们将不会被返回。

SELECT i.*, o.organ_name, o.organ_logo, vtable.*
FROM heroku_056eb661631f253.op_ideas i
JOIN
    (SELECT
        COUNT(v.agree) as agree,
        COUNT(v.disagree = 1 or null) as disagree,
        COUNT(v.obstain = 1 or null) as abstain
    FROM op_idea_vote v, op_ideas i
    WHERE v.idea_id = i.idea_id
    ) AS vtable
  LEFT JOIN op_organs o ON i.post_type = o.organs_id
于 2012-10-13T16:03:56.390 回答