MySQL - 在一个连接表中计算不同条件下的不同字段

时间:2010-11-11 10:51:32

标签: php mysql join count

有一个名为Table1的假设表,其中包含以下列:

  • ID
  • 条件1
  • 条件2
  • joinable_key

还有另一个,Main_Table,其ID与第一个中的joinable_key相对应。

我想以这样的方式加入它们,我可以根据条件1和条件2分别计算Table1的行数 - 也就是说,我希望能够执行“count(Table1.condition1)as first_condition,count(Table1.condtion2)as second_condition“on select query。

查询可能看起来像这样:

SELECT  Main_Table.some_column, COUNT(Table1.condition1) AS first_condition, COUNT(Table1.condtion2) AS second_condition
FROM  Main_Table
LEFT JOIN Table1 AS T1 on (T1.joinable_key = Main_Table.id AND T1.condition1 = 'something')
LEFT JOIN Table1 AS T2 on (T2.joinable_key = Main_Table.id AND T2.condition2 = 'something else')
GROUP BY (Main_Table.id)

然而,当执行此操作时,两个计数结果相等,并且实际上彼此相乘。 必须将所有结果包含在最终输出中 - 包括那些没有Table1中任何条目的结果 - 也就是说,如果Table1中没有行,joinable_key等于Main_Table.id,则也需要包含它。

在有人建议实际做两个单独的查询并通过PHP处理它之前 - 是的,我知道为什么以及如何完成它,但我的目标是找出这个多重计数是否可以在一个查询中完成

谢谢

2 个答案:

答案 0 :(得分:4)

SELECT some_column,
       (SELECT COUNT(1)
          FROM Table1
         WHERE mt.id = joinable_key
           AND condition1 = 'something'
       ) AS first_condition,
       (SELECT COUNT(1)
          FROM Table1
         WHERE mt.id = joinable_key
           AND condition2 = 'something else'
       ) AS second_condition
  FROM MainTable mt

答案 1 :(得分:0)

SELECT  Main_Table.some_column,
        SUM(t1.condition1 = 'something') AS first_condition,
        SUM(t1.condition2 = 'something_else') AS second_condition
FROM    Main_Table
LEFT JOIN
        Table1 AS t1
ON      t1.joinable_key = Main_Table.id
        AND
        (
        t1.condition1 = 'something'
        OR
        t1.condition2 = 'something else'
        )
GROUP BY
        Main_Table.id

如果condition1condition2都具有选择性,则此语法可能更有效:

SELECT  Main_Table.some_column,
        (
        SELECT  COUNT(*)
        FROM    table1 t1
        WHERE   t1.joinable_key = main_table.id
                AND t1.condition1 = 'something'
        ),
        (
        SELECT  COUNT(*)
        FROM    table1 t1
        WHERE   t1.joinable_key = main_table.id
                AND t1.condition2 = 'something_else'
        )
FROM    Main_Table

您应该创建以下索引:

table1 (id, condition1)
table1 (id, condition2)

让它快速工作。