MYSQL限制左连接查询

时间:2017-01-16 12:09:05

标签: mysql left-join sql-order-by limit

我有一个查询,它使用一些左连接来恢复数据。困境是我希望LIMIT以及ORDER BY来自其中一个左连接的结果,从而限制了返回的总行数。

我尝试订购和限制的表格为table4

我的查询:

SELECT SQL_CALC_FOUND_ROWS e.meta_1, a.requestid, b.clientid, c.job_description, d.forename
FROM quotations_request AS a 

 LEFT JOIN table1 AS b ON (a.assigned_to = b.userid) 
 LEFT JOIN table2 AS c ON (a.job_costing = c.jobid) 
 LEFT JOIN table3 AS d ON (a.clientid = d.clientid) 
 LEFT JOIN table4 AS e ON (e.quotationid = a.requestid)

 WHERE a.archived = '0' AND (e.meta_1 = LCASE('requested') )

我尝试了什么:

SELECT SQL_CALC_FOUND_ROWS statuss.meta_1, a.requestid, b.clientid, c.job_description, d.forename,
 FROM quotations_request AS a 

 LEFT JOIN table1 AS b ON (a.assigned_to = b.userid) 
 LEFT JOIN table2 AS c ON (a.job_costing = c.jobid) 
 LEFT JOIN table3 AS d ON (a.clientid = d.clientid) 
 LEFT JOIN (Select meta_1 from table4 where quotationid = a.requestid ORDER BY uploaded_date DESC LIMIT 0, 1) 
 as statuss ON (statuss.quotationid = a.requestid)

 WHERE a.archived = '0' AND (statuss.meta_1 = LCASE('requested') )

结果:

在尝试上述操作后,我收到一条错误,指出a.requestid在where子句中未知(对于最后一个左连接)

1 个答案:

答案 0 :(得分:1)

试试这个:

<a>

用户变量@rn和@qid用于从table4中找到最新的uploaded_date的前1行,然后将其与其他表连接