I'm trying to get data from 3 tables in one query. Those tables are for storing and displaying user messages. Each user can log in and request all his inbox messages. The user id is avaliable from the PHP session and parameter type=1 gets passed in the php request which means the request to show inbox (type=2 would be info messages etc).
First table called email has id
, subject
, body
and date
Second table called email_routing has message_id
, sender_email_id
, receiver_email_id
, basket
, type
. The message_id
refers to id
of the message in email table.
Sender and receiver id refers to email ids from the third table that called people_emails. It consist of id
(that what sender and receiver email id refer to), internal_user_id
(that's what is avaliable from PHP session), email
and people_id
(each person may have several emails in the contact book so I store people and their emails in separate tables, but this last column if not of our interest here).
So I can figure out how I would do my queries in sequence and just for one row result:
Fist I would get user email id based on his user_id from PHP session:
$X = SELECT `id` from `people_emails` WHERE `internal_user_id`=$_conf[user]->id;
$X is not a proper coding, let's say it is a variable I would eventually get.
Then I can query the email_routing table to all the messages addressed to that user:
$Y = SELECT `message_id`, `sender_email_id`, `receiver_email_id` FROM `email_routing` WHERE `receiver_email_id`=$X[id] and `type`=$_REQUEST[type];
Having list of the message_id's I can now query the email table for the messages content:
$R = SELECT `subject`, `body`, `date` FROM `email` WHERE `id`=$Y[message_id];
Ok, then I need to "translate" the "from" addresses from its id which I got from email_routing table, so it is:
$Z_from = SELECT `email` FROM `people_emails` WHERE `id`=$X[sender_email_id];
I now have all the data for one row. Then I need to put all together which will be
$Z_from + $R[subject] + $R[body] + $R[date]
I need to have it as one list of results which then gets passed to bootstrap datatables plugin for displaying and searching. I can't seem to figure that one out. Please help.