匹配的記錄考慮以下4個表MySQL的次數從多個表
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
哇。工程奇蹟。您可能希望在每個FROM – MonoThreaded
之前修復額外的','順便說一下,如果沒有索引,查詢需要0.5s,這對我來說非常合適。 – MonoThreaded
如果你喜歡0.5超過0.005,對我來說沒問題。我不明白爲什麼人們不想把索引放在表格中,這就是他們的目的,以提高效率。 –