MySQL - 如果LEFT OUTER JOIN中不存在行,则排除行

时间:2012-05-15 09:11:43

标签: mysql database

我有一个SQL查询,它在某种程度上正常工作。

LEFT OUTER JOIN工作正常,但如果mdl_modules或mdl_resource中没有记录,则会出现NULL。

如何从mdl_course_modules中排除记录哪一个LEFT OUTER JOIN中没有记录?

我认为我会使用ISNULL()但不确定正确的语法是否与我的查询合并。

这是我的问题:

SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", "cm.id AS theid, m.name AS mname, r.name AS resourcename, r.summary AS resourcesummary,
        FROM_UNIXTIME(cm.added, '%D %M %Y') AS dateadded")."
        FROM mdl_course_modules cm 
        LEFT OUTER JOIN mdl_modules m on cm.module = m.id
        LEFT OUTER JOIN mdl_resource r on cm.instance = r.id
        WHERE m.name = 'resource' AND cm.visible = 1
        $scourse
        $sWhere
        $sOrder
        $sLimit

2 个答案:

答案 0 :(得分:1)

通常情况下,这可以通过切换到INNER JOIN来实现,但MySql中的INNER JOIN相当于CROSS JOIN,因此实际上无济于事。

要解决此问题,请使用WHERE

添加所需的ISNULL条件
SELECT ...
    FROM_UNIXTIME(cm.added, '%D %M %Y') AS dateadded")."
    FROM mdl_course_modules cm 
    LEFT OUTER JOIN mdl_modules m on cm.module = m.id
    LEFT OUTER JOIN mdl_resource r on cm.instance = r.id
    WHERE m.name = 'resource' AND cm.visible = 1
        && (!ISNULL(m.name) || !ISNULL(r.name))

答案 1 :(得分:1)

WHERE m.name ='resource'AND cm.visible = 1 AND(m.id IS NOT NULL或r.id IS NOT NULL)