有些员工没有组织。
explain SELECT DISTINCT
e.*
FROM
employee e
LEFT JOIN
employee_orgn eo ON eo.employee_id = e.id
LEFT JOIN
orgn o ON o.id = eo.orgn_id
WHERE
e.state != 'deleted'
AND e.state != 'hidden'
AND (o.state != 'hidden' OR o.state IS NULL)
ORDER BY e.id DESC
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | e |all | NULL | NULL |NULL | NULL | 12792 |Using where;USing tempory;Using filesort |
| 1 | SIMPLE | eo |index | PRIMARY | idx_orgn_id |8 | NULL | 13226 |Using index:Distinct |
| 1 | SIMPLE | o |eq_ref | PRIMARY | PRIMARY |8 | eo.orgn_id | 1 |Using where:Distinct |
谢谢。
答案 0 :(得分:0)
我建议重写查询-摆脱select distinct
。我认为这是您想要的逻辑:
SELECT e.*
FROM employee e
WHERE e.state not in ('deleted', 'hidden')
NOT EXISTS (SELECT 1
FROM employee_orgn eo JOIN
orgn o
ON o.id = eo.orgn_id AND o.state = 'hidden'
WHERE eo.employee_id = e.id
)
ORDER BY e.id DESC;
对于此查询,您需要在employee_orgn(employee_id, orgn_id)
和orgn(id, state)
上建立索引。
答案 1 :(得分:0)
您不应在WHERE
子句中保留联接的表上放置条件。而是将它们放在ON
子句中。然后,您无需使用OR o.state IS NULL
,这会导致优化程序出现问题。
SELECT DISTINCT
e.*
FROM
employee e
LEFT JOIN
employee_orgn eo ON eo.employee_id = e.id
LEFT JOIN
orgn o ON o.id = eo.orgn_id AND o.state != hidden
WHERE
e.state NOT IN ('deleted', 'hidden')
ORDER BY e.id DESC