Populate empty database columns with !empty older row columns

时间:2015-09-01 21:21:10

标签: mysql select merge rows

Lets say I have a database containing the following rows:

id (auto_incremented) | id_person | first_name | last_name | phone          | email
-----------------------------------------------------------------------------
1                     | 12        | kevin      | smith     |                | kevin@hotmail.com
2                     | 12        | kevin      | smith     | 1-800-123-4567 | 
3                     | 33        | joe        | jones     | 1-800-765-4321 | 
4                     | 33        | joe        | thompson  |                | joe@hotmail.com
5                     | 33        | joe        | thompson  |                | newjoe@hotmail.com

Based on id_person, I want to output the following in a single query:

id | id_person | first_name | last_name | phone          | email
-----------------------------------------------------------------------------
2  | 12        | kevin      | smith     | 1-800-123-4567 | kevin@hotmail.com
5  | 33        | joe        | thompson  | 1-800-765-4321 | newjoe@hotmail.com

So basically, I just want to take the newest row values, and if they are empty, grab the values from the first row which isn't empty.

How do I do this? Hope this makes sense.

2 个答案:

答案 0 :(得分:0)

SELECT id_person, subQ.lastID
    , GROUP_CONCAT(IF(subQ.lastFieldXId = tblFields.ID, tblFields.fieldX, NULL)) AS fieldX
    , GROUP_CONCAT(IF(subQ.lastFieldYId = tblFields.ID, tblFields.fieldY, NULL)) AS fieldY
    [, ...]
FROM
(SELECT id_person
   , MAX(id) AS lastID
   , MAX(IF(IFNULL(fieldX, '') = '', 0, id) AS lastFieldXId
   , MAX(IF(IFNULL(fieldY, '') = '', 0, id) AS lastFieldYId
[, ....]
FROM theTable
GROUP BY id_person) AS subQ
LEFT JOIN theTable AS tblFields USING (id_person)
;

The LEFT JOIN may or may not be faster as

LEFT JOIN theTable AS tblFields 
ON tblFields.ID IN (subQ.lastFieldXId, subQ.lastFieldYId [, ...])

There is probably also a way using session variables, but I don't have the energy...

答案 1 :(得分:0)

select * from(
select p1.id,p1.id_person,p1.first_name,p1.last_name,
ifnull(p1.phone,p2ph.phone) phone ,ifnull(p1.email,p3em.email) email

from person p1
left join person p2ph on(p1.id_person=p2ph.id_person and p2ph.phone is not null)
left join person p3em on(p1.id_person=p3em.id_person and p3em.email is not null)
order by id_person,p1.id desc,p2ph.id desc,p3em.id desc 
  )t group by id_person;

verify at http://sqlfiddle.com/#!9/d2f44/6