这个解决方案比 Mark 的更冗长,但应该更有效,因为它避免使用临时表......
SELECT
es1.emp_no,
IF(es2.is_active=1, es2.sal_id, es1.sal_id) AS sal_id,
IF(es2.is_active=1, es2.value, es1.value) AS value,
IF(es2.is_active=1, es2.effective_date, es1.effective_date) AS effective_date,
IF(es2.is_active=1, es2.is_active, es1.is_active) AS is_active
FROM employee_salary es1
LEFT JOIN employee_salary es2 ON (es2.emp_no=es1.emp_no AND es2.sal_id=2)
WHERE es1.sal_id=1;
...产生...
+--------+--------+-----------+----------------+-----------+
| emp_no | sal_id | value | effective_date | is_active |
+--------+--------+-----------+----------------+-----------+
| 817 | 1 | DED914E3B | 01/04/2013 | 1 |
| 820 | 2 | EA42574E4 | 02/04/2013 | 1 |
+--------+--------+-----------+----------------+-----------+
...并为此产生 EXPLAIN ...
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | es1 | ALL | NULL | NULL | NULL | NULL | 4 | Using where |
| 1 | SIMPLE | es2 | ALL | NULL | NULL | NULL | NULL | 4 | |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
...与马克的...相比
+----+-------------+-----------------+------+---------------+------+---------+------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------------+------+---------------+------+---------+------+------+----------------------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 2 | |
| 1 | PRIMARY | es | ALL | NULL | NULL | NULL | NULL | 4 | Using where; Using join buffer |
| 2 | DERIVED | employee_salary | ALL | NULL | NULL | NULL | NULL | 4 | Using where; Using temporary; Using filesort |
+----+-------------+-----------------+------+---------------+------+---------+------+------+----------------------------------------------+
您可以删除IF
您实际上不需要值的任何子句。