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!)
preguntado el 24 de agosto de 12 a las 00:08
Why not join
parent columna al
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
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
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!