将派生表的右连接替换为左连接

时间:2011-08-19 14:17:13

标签: mysql left-join derived-table

如何使用左连接编写此查询。由于我使用的框架不支持右连接,我需要重写查询。任何人都可以建议我一个可能的解决方案。

select Audit.history_id,Audit.field,modifiedtime,operation from Audit right join (select History.history_id from History where refid=2000000020088 order by
modifiedtime limit 5) as Hist on Audit.history_id=Hist.history_id;

    desc Audit
    +------------------+------------+------+-----+---------+-------+
    | Field            | Type       | Null | Key | Default | Extra |
    +------------------+------------+------+-----+---------+-------+
    | AUDIT_ID         | bigint(19) |      | PRI | 0       |       |
    | HISTORY_ID       | bigint(19) |      | MUL | 0       |       |
    | FIELD            | varchar(50)       |     |         |       |
    | OLD_VALUE        | varchar(50)| YES  |     | NULL    |       |
    | NEW_VALUE        | varchar(50)| YES  |     | NULL    |       |
    +------------------+------------+------+-----+---------+-------+

desc History
+---------------+-------------+------+-----+---------------------+-------+
| Field         | Type        | Null | Key | Default             | Extra |
+---------------+-------------+------+-----+---------------------+-------+
| HISTORY_ID    | bigint(19)  |      | PRI | 0                   |       |
| REFID         | bigint(19)  |      | MUL | 0                   |       |
| OPERATION     | varchar(50) | YES  |     | NULL                |       |
| MODIFIED_TIME | datetime    |      |     | 0000-00-00 00:00:00 |       |
+---------------+-------------+------+-----+---------------------+-------+

3 个答案:

答案 0 :(得分:1)

只需切换左连接的关系:

  

实际上,很少使用明确的右外连接,因为它们总是可以用左外连接替换(切换表顺序)并且不提供其他功能。

来源:Wikipedia.org

答案 1 :(得分:1)

select 
    Audit.history_id,Audit.field,modifiedtime,operation 
from    
    (
        select History.history_id 
        from History where refid=2000000020088 
        order by modifiedtime limit 5            
    ) as Hist 
    left join Audit on (Audit.history_id = Hist.history_id);

答案 2 :(得分:0)

不确定这是否会产生与现在相同的输出,但它可能会给你正确的想法:

选择Audit.history_id,Audit.field,History.modifiedtime,History.operation
来自历史 left join审计Audit.history_id = History.history_id
其中History.refid = 2000000020088
按History.modifiedtime订购