尽管Nulls / None和Duplicates,但仍然获得一行

时间:2013-06-12 20:17:01

标签: mysql

我有一个接近我想要但不完全符合的查询:

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或e记录使用MAX ID,如果没有使用“ - ”

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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