PHP join three tables when if the data is not in one of them
I am working on joining three tables together,开发者_如何学运维 but in one of the tables no information will be in there, unless the user opens the email we sent them
I am currently using this sql but it seems not to work correctly
SELECT email.senton, customer.*, count(tracker.viewed) as viewed
FROM email_sent AS email, customer_detail AS customer, email_tracker AS tracker
WHERE email.customer_id = customer.customer_id
AND customer.Email = tracker.emailaddress
AND customer.LeadOwnerId = '{$this->userid}'
This is due to the table email_tracker may not have the customers info in it, unless the customer has opened the email
Try this:
SELECT email.senton, customer.*, COUNT(tracker.viewed) as viewed
FROM email_sent email INNER JOIN customer_detail customer
ON email.customer_id = customer.customer_id
LEFT JOIN email_tracker tracker
ON customer.Email = tracker.emailaddress
WHERE customer.LeadOwnerId = '{$this->userid}'
The LEFT JOIN clause is used to always get columns on the left part and columns on the right part if they exist in the join...
EDITED according to your comment:
Try to change COUNT(tracker.viewed)
part with
CASE
WHEN tracker.emailaddress IS NOT NULL THEN COUNT(tracker.viewed)
ELSE 0
END
as viewed
I'm not sure it works, I cannot test it, but give it a try
The behavior that you want is the LEFT OUTER JOIN
(also known as LEFT JOIN
). It just set's the value to NULL
if the row doesn't exist in the other table.
SELECT email.senton, customer.*, COUNT(tracker.viewed) AS viewed
FROM email_sent AS email
JOIN customer_detail AS customer USING(customer_id)
LEFT OUTER JOIN email_tracker AS tracker ON customer.Email = tracker.emailaddress
WHERE customer.LeadOwnerId = '{$this->userid}'
PS: It's generally a better idea to use JOIN
s instead of a Cartesian product (what you did with ,
).
精彩评论