MySQL Parent details if it is a child account
Frecuentes
Visto 70 veces
2
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 a.id = e.account_id), but only parent accounts have emails. That is to say, Bravo-A's email is Bravo's.
If I have the accounts.id number, is it possible to write a query that would give me the emails.email 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!)
3 Respuestas
4
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 a.id = e.account_id
LEFT JOIN `emails` b
ON a.parent = b.account_id
Respondido 24 ago 12, 00:08
1
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
0
Answered it myself!
SELECT a.id, e.email
FROM account a
INNER JOIN emails.e
ON e.account_id = IF(a.parent <> 0, a.parent, a.id)
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 mysql sql join or haz tu propia pregunta.
So you want to return Bravo's email if id = 3? - Michael Berkowski
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)? - Xavier Holt
@XavierHolt i think that's the OP want, the parent's email address is also the child's email address - John Woo