考虑以下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; +----+-------------+--------+------+--------------- +------+---------+------+--------+-----------+ | 编号 | 选择类型 | 表| 类型 | 可能的键 | 关键 | key_len | 参考 | 行 | 额外 | +----+-------------+--------+------+--------------- +------+---------+------+--------+-----------+ | 1 | 简单 | 电子| 全部 | 空 | 空 | 空 | 空 | 1083 | 使用位置 | | 1 | 简单 | ○ | 全部 | 空 | 空 | 空 | 空 | 90201 | | +----+-------------+--------+------+--------------- +------+---------+------+--------+-----------+ 2 行(0.04 秒)
相反的效果要好得多,但不能扩展到多个表
SELECT e.id,count(t1,id) FROM table1 AS t1 LEFT JOIN entity AS e ON t1.ei=e.id