2013-12-08 196 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;