2013-12-08 136 views
0

我有以下查询,它检索记录列表并从另一个表中获取每条记录的最新阶段。MySQL限制子查询

SELECT leads.lead_id AS id, leads.fields, leads.date, users.name AS introducer, (SELECT lead_stage_id FROM lead_stage_history WHERE lead_stage_history.lead_id=leads.lead_id ORDER BY date_added DESC LIMIT 1) stage FROM leads, users WHERE leads.introducer_id=users.user_id AND leads.account_id=1 ORDER BY date DESC;

我期待限制由舞台列返回的值?

我想过滤记录列表只显示某个阶段的记录。

谢谢。

回答

0

您可以通过使用having子句中的MySQL这样做:

SELECT leads.lead_id AS id, leads.fields, leads.date, users.name AS introducer, 
     (SELECT lead_stage_id 
     FROM lead_stage_history 
     WHERE lead_stage_history.lead_id = leads.lead_id 
     ORDER BY date_added DESC 
     LIMIT 1 
    ) stage 
FROM leads join 
    users 
    on leads.introducer_id=users.user_id 
WHERE leads.account_id=1 
HAVING stage = 'XXX' 
ORDER BY date DESC; 

在其他数据库,你WOU

select t.* 
from (SELECT leads.lead_id AS id, leads.fields, leads.date, users.name AS introducer, 
      (SELECT lead_stage_id 
       FROM lead_stage_history 
       WHERE lead_stage_history.lead_id = leads.lead_id 
       ORDER BY date_added DESC 
       LIMIT 1 
      ) stage 
     FROM leads join 
      users 
      on leads.introducer_id=users.user_id 
     WHERE leads.account_id = 1 
    ) t 
where stage = 'XXX' 
ORDER BY date DESC;