从2个表中检索数据时,LEFT JOIN无法正常工作

时间:2011-10-30 16:01:58

标签: mysql sql left-join

我有2个表,名为subscriptionstags。一个月内,我将不得不为每个订单创建标签。

我必须在给定的月份(2011-10-01或2011-09-01等)列出没有标签的订阅。此查询返回0条记录:

   SELECT s.id, s.active, s.status 
     FROM asw_subscriptions as s 
LEFT JOIN asw_tags as t ON s.id = t.subscription_id 
    WHERE t.subscription_id IS NULL 
      AND t.deliveryDate = '2011-10-01' 
      AND s.status = '2' 
      AND s.active = '1' 
 ORDER BY s.id DESC 
    LIMIT 0, 25

表格结构


订阅 = id(int / auto),活动(枚举:0,1),状态(枚举:0,1)

标记 = id(int / auto),deliveryDate(date),tagNumber

3 个答案:

答案 0 :(得分:4)

问题在于clausule

t.deliveryDate = '2011-10-01' AND

你没有在左边录制,因为条件'IS NULL'消除了LEFT JOIN'ed记录。 因此,上述条件将消除所有连接产品,因为永远不会成立(t.deliveryDate中将始终为null。

尝试这样的事情:

SELECT s.id, s.active, s.status 
     FROM asw_subscriptions as s 
WHERE s.status = '2' 
      AND s.active = '1' 
      AND NOT EXISTS (
         SELECT 1
         FROM asw_tags as t
         WHERE s.id = t.subscription_id
         AND t.deliveryDate = '2011-10-01'          
      )
 ORDER BY s.id DESC 
    LIMIT 0, 25

答案 1 :(得分:2)

问题是您在检查标记是否存在的同一查询上检查标记日期。

试试这个:

SELECT s.id, s.active, s.status 
FROM
    asw_subscriptions as s
    LEFT JOIN (
        SELECT subscription_id
        FROM asw_tags
        WHERE deliveryDate = '2011-10-01'
    ) as t ON s.id = t.subscription_id 
WHERE 
    t.subscription_id IS NULL
    AND s.status = '2'
    AND s.active = '1' 
ORDER BY s.id DESC
LIMIT 0, 25

答案 2 :(得分:1)

只是意识到在WHERE下指定条件 - 你实现INNER JOIN逻辑,它不是你所期望的。因此,将整个WHERE部分放在OUTER JOIN的ON下:

 ... ON s.id = t.subscription_id 
 AND t.subscription_id IS NULL AND 
 t.deliveryDate = '2011-10-01' AND 
 s.status = '2' AND 
 s.active = '1'