2013-06-12 39 views
0

我有一個查詢是接近我想要什麼,但不完全:獲取一條記錄後面,儘管空值/無,重複

SELECT DISTINCT p.id, 
       Ifnull(p.last_name, '--')   last_name, 
       Ifnull(p.first_name, '--')  first_name, 
       Ifnull(p.city, '--')    city, 
       Ifnull(p.state, '--')    state, 
       Ifnull(e.full_name, '--')   full_name, 
       Ifnull(o.current_step, '--')  current_step, 
       Ifnull(o.current_step_date, '--') current_step_date 
FROM prospect AS p 
     JOIN opportunity AS o 
     ON o.prospect_id = p.id 
     JOIN employee AS e 
     ON p.id_ofproducer = e.id 
WHERE p.id = 1234 

我希望能與P獲取該行回來

注:如果有超過一個O或電子記錄使用MAX ID,如果沒有,則使用「 - 」

+1

如果'opportunity'或'employee'中沒有匹配的行,則需要使用'LEFT JOIN'。 – Barmar

回答

1

你需要一個left join那裏有沒有記錄處理情況。而且,您需要找到oe記錄的最大值。其實,你不應該對e記錄有任何問題,因爲你正在加入這個ID。這裏是制定查詢的一種方法:

SELECT DISTINCT p.id, 
       Ifnull(p.last_name, '--')   last_name, 
       Ifnull(p.first_name, '--')  first_name, 
       Ifnull(p.city, '--')    city, 
       Ifnull(p.state, '--')    state, 
       Ifnull(e.full_name, '--')   full_name, 
       Ifnull(o.current_step, '--')  current_step, 
       Ifnull(o.current_step_date, '--') current_step_date 
FROM prospect AS p 
     left JOIN opportunity AS o 
     ON o.prospect_id = p.id and 
      o.id = (select id from opportunity o2 where o2.prospect_id = p.id order by id desc limit 1) 
     left JOIN employee AS e 
     ON p.id_ofproducer = e.id 
WHERE p.id = 1234 
0
SELECT p.id, 
     Ifnull(p.last_name, '--')   last_name, 
     Ifnull(p.first_name, '--')  first_name, 
     Ifnull(p.city, '--')    city, 
     Ifnull(p.state, '--')    state, 
     Ifnull(e.full_name, '--')   full_name, 
     Ifnull(o.current_step, '--')  current_step, 
     Ifnull(o.current_step_date, '--') current_step_date 
FROM prospect AS p 
     JOIN opportunity AS o 
     ON o.prospect_id = p.id 
     JOIN employee AS e 
     ON p.id_ofproducer = e.id 
WHERE p.id = 1234 
ORDER BY o.prospect_id DESC, e.id DESC 
LIMIT 1