【发布时间】:2015-11-03 10:56:27
【问题描述】:
我想加入一个具有时间单位的表格(注意:这些不是连续的)
Time 1
Time 2
…带有部门…
的表格Department 1
Department 2
...为了匹配observations表,但只选择X类型的那些...
Time unit Department id Observation Type
Time 1 Department 1 6 X
Time 2 Department 2 5 X
Time 2 Department 2 4 Y
…最终得到一个这样的表——缺失的观察用 0 或 NULL 填充
Time unit Department id Observation
Time 1 Department 1 6
Time 2 Department 1 0
Time 1 Department 2 0
Time 2 Department 2 5
这可以完成工作,但速度很慢,所以我确信肯定有比以下更好的方法?
SELECT timeunits.time_unit, departments.department_id, observations.observation
FROM timeunits
CROSS JOIN departments
LEFT JOIN (
SELECT observations.time_unit, observations.department_id, observations.observation
FROM observations
WHERE observations.type='X'
) as observations
ON timeunits.time_unit=observations.time_unit
AND departments.department_id=observations.department_id
解释:
+----+-------------+--------------+-------+---------------+-------------+---------+---------------------------------------------+--------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------+-------+---------------+-------------+---------+---------------------------------------------+--------+----------------------------------------------------+
| 1 | PRIMARY | time_units | ALL | NULL | NULL | NULL | NULL | 200 | NULL |
| 1 | PRIMARY | departments | index | NULL | PRIMARY | 4 | NULL | 500 | Using index; Using join buffer (Block Nested Loop) |
| 1 | PRIMARY | <derived2> | ref | <auto_key0> | <auto_key0> | 263 | observations.time_units.time_unit, | | |
| | | | | | | | observations.departments.department_id | 600 | Using where |
| 2 | DERIVED | observations | ref | type | type | 258 | const | 100000 | Using index condition |
+----+-------------+--------------+-------+---------------+-------------+---------+---------------------------------------------+--------+----------------------------------------------------+
【问题讨论】: