MySQL Parent details if it is a child account

I have a table with data like the following

id    name      created         parent
1     Alpha     11385209583     0
2     Bravo     11385209619     0
3     Bravo-A   11385209701     2
4     Bravo-B   11385209777     2

such that Bravo-A and Bravo-B are children of Bravo.

There is another table with email addresses in it (accounts a JOIN emails e ON = e.account_id), but only parent accounts have emails. That is to say, Bravo-A's email is Bravo's.

If I have the number, is it possible to write a query that would give me the field for the correct account (where account_id = 1 when id is 1, account_id = 2 when id is 2, 3, or 4)?

(My apologies if this is a little verbose or not to the point, I was having trouble verbalizing it!)

preguntado el 24 de agosto de 12 a las 00:08

So you want to return Bravo's email if id = 3? -

Can only nivel superior accounts have e-mails, or all con el futuro bebé accounts (for example, if Bravo-B got some children, could it then have an e-mail)? -

@XavierHolt i think that's the OP want, the parent's email address is also the child's email address -

3 Respuestas

Why not join acount's parent columna al email?

SELECT  a.*, 
        e.emailadd as parentEAdd, 
        COALESCE(b.emailadd,'') as ChildEAdd -- can contain null values when 
                                             -- parentID is 0
FROM    `accounts` a 
             INNER JOIN `emails` e 
                  ON = e.account_id
             LEFT JOIN `emails` b
                  ON a.parent = b.account_id

Respondido 24 ago 12, 00:08

The easiest way is to put another field in accounts table (say "mail_id"), store each email's id there and do joins based on that field. That way the childs may have the same or different mails if you want

Respondido 24 ago 12, 00:08

Answered it myself!

FROM account a 
         INNER JOIN emails.e 
              ON e.account_id = IF(a.parent <> 0, a.parent,

The thing I find with SQL is that there is always a more elegant way!

Respondido 24 ago 12, 00:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.