0

我正在将三个表连接在一起,但是在其中一个表中没有任何信息,除非用户打开我们发送给他们的电子邮件

我目前正在使用这个 sql,但它似乎无法正常工作

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}'

这是因为 email_tracker 表中可能没有客户信息,除非客户打开了电子邮件

4

2 回答 2

1

试试这个:

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}'

LEFT JOIN子句用于始终获取左侧的列和右侧的列(如果它们存在于连接中)...

根据您的评论编辑:
尝试更改COUNT(tracker.viewed)部分

CASE
    WHEN tracker.emailaddress IS NOT NULL THEN COUNT(tracker.viewed)
    ELSE 0
END
    as viewed 

我不确定它是否有效,我无法测试它,但试一试

于 2011-09-22T07:10:25.677 回答
1

您想要的行为是LEFT OUTER JOIN(也称为LEFT JOIN)。NULL如果该行在另一个表中不存在,它只是将值设置为。

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}'

JOINPS:使用s 而不是笛卡尔积(你用 s 做了什么)通常是一个更好的主意,

于 2011-09-22T07:11:39.370 回答