For example: A contract table table table t_contract B contract audit table t_contract_audit . The two tables associated contract_id. And a contract a number of audit records. Requirements: A state contract, B latest audit record the results..
简单:A 1--key--n B ---》A.*+B.*。
Scenario 1 :
A separate table as the main query traversing List, each query corresponding to a contract Table B, creating reverse chronological order according to the first take.
Performance :
If paging query, such as 10 a, this program in two steps, clear thinking, SQL simple , no "large amount of data associated with multi-table queries slow."
Scenario 2 :
1) Table B treatment, in accordance with contract_id leaving only the creation of a new time. (Of course, sub-queries can, personally think that is better inner join is easy to understand)
SELECT
a.*
FROM
t_contract_audit a
INNER JOIN ( SELECT contract_id, max( create_time ) create_time FROM t_contract_audit GROUP BY contract_id ) b ON a.contract_id = b.contract_id AND a.create_time = b.create_time
2) The first step as the processing result R Table: select A *, R. * from A left join R on A.contract_id = R.contract_id.
SELECT h.*,r.* FROM t_contract h left JOIN (SELECT a.* FROM t_contract_audit a INNER JOIN ( SELECT contract_id, max( create_time ) create_time FROM t_contract_audit GROUP BY contract_id ) b ON a.contract_id = b.contract_id AND a.create_time = b.create_time ) r ON h.contract_id = r.contract_id where h.sale_id=2702 and h.contract_status IN (8,9) order by h.create_time desc
Performance :
Get a SQL, SQL has some complexity and magnitude if the table is large, there is a risk ! Test yourself in the best performance from the library about.