繁体   English   中英

MySQL计数来自多个表的匹配记录

[英]MySQL Count matching records from multiple tables

考虑以下4个表

entity  table1        table2        table3       
------  ------------- ------------- -------------
id      ei(entity.id) ei(entity.id) ei(entity.id)
name    something     somethingelse yetanother

如何在所有三个表中找出实体用法 ,如表示

---------------------
| id | t1 | t2 | t3 |
---------------------
|  1 | 14 | 23 |  0 |
|  2 | 66 |  9 |  5 |
...

我的原始方法是从实体中选择然后离开加入其他表但MySQL似乎不喜欢它

SELECT e.id,count(t1.id) FROM entity AS e LEFT JOIN table1 AS t1 on e.id=t1.ei;

编辑:这是1表的输出

mysql> explain select e.id,count(o.id) from entity e left join table1 t1 on e.id=o.ei where e.ty=3;
+----+-------------+-------+------+---------------+------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows  | Extra       |
+----+-------------+-------+------+---------------+------+---------+------+-------+-------------+
|  1 | SIMPLE      | e     | ALL  | NULL          | NULL | NULL    | NULL |  1083 | Using where |
|  1 | SIMPLE      | o     | ALL  | NULL          | NULL | NULL    | NULL | 90201 |             |
+----+-------------+-------+------+---------------+------+---------+------+-------+-------------+
2 rows in set (0.04 sec)

相反的工作要好得多,但不能扩展到多个表

SELECT e.id,count(t1,id) FROM table1 AS t1 LEFT JOIN entity AS e ON t1.ei=e.id
SELECT  a.ID, 
        COUNT(b.ei) t1,
        COUNT(c.ei) t2,
        COUNT(d.ei) t3
FROM    entity a
        LEFT JOIN table1 b
            ON a.id = b.ei
        LEFT JOIN table2 c
            ON a.id = c.ei
        LEFT JOIN table3 d
            ON a.ID = d.ei
GROUP BY a.ID
select select 
e.id,
sum(case when t1.name is null then 0 else 1 end) t1,
sum(case when t2.name is null then 0 else 1 end) t2,
sum(case when t3.name is null then 0 else 1 end) t3
from
entity e left join table1 t1 on e.id=t1.ei left join table2 t2 on e.id=t2.ei left join table3 t3 on e.id=t3.ei
group by e.id

==

SQL小提琴演示

另一种重写此查询的方法。

分别对每个表进行分组和计数,然后加入:

SELECT  a.id, 
        COALESCE(b.t1, 0) AS t1,
        COALESCE(c.t2, 0) AS t2,
        COALESCE(d.t3, 0) AS t3
FROM
        entity a
    LEFT JOIN
        ( SELECT ei,
                 COUNT(*) AS t1
          FROM table1
          GROUP BY ei
        ) AS b
            ON a.id = b.ei
    LEFT JOIN
        ( SELECT ei,
                 COUNT(*) AS t2
          FROM table2
          GROUP BY ei
        ) AS c
            ON a.id = c.ei
    LEFT JOIN
        ( SELECT ei,
                 COUNT(*) AS t3
          FROM table3
          GROUP BY ei
        ) AS d
            ON a.id = d.ei
  ;

如果你没有,你肯定应该在3个表中的每个表上添加索引(ei)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM