我如何在`JOIN`上使用`WHERE`?

时间:2013-04-17 16:03:03

标签: mysql sql

我有这个sql代码

SELECT sites.id, sites.url, GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories
        FROM sites
        LEFT JOIN categories_data ON sites.id = categories_data.sites_id WHERE categories_data.deleted=0
        LEFT JOIN categories ON categories_data.categories_id = categories.id WHERE categories.deleted=0
        WHERE sites.deleted=0 GROUP BY sites.id'

返回此错误

Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN categories ON categories_data.categories_id = categories.id WHERE cate' at line 4 [ SELECT sites.id, sites.url, GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories FROM sites LEFT JOIN categories_data ON sites.id = categories_data.sites_id WHERE categories_data.deleted=0 LEFT JOIN categories ON categories_data.categories_id = categories.id WHERE categories.deleted=0 WHERE sites.deleted=0 GROUP BY sites.id ]

那么,我如何在WHERE上使用JOIN

感谢。

3 个答案:

答案 0 :(得分:2)

您无法在联合表的WHERE子句中添加ON子句。用条件运算符( AND / OR ),

分隔它们
SELECT sites.id, 
       sites.url, 
       Group_concat(categories.name, '|', categories.color SEPARATOR ',') AS 
       categories 
FROM   sites 
       LEFT JOIN categories_data 
              ON sites.id = categories_data.sites_id 
                 AND categories_data.deleted = 0                  -- <<== HERE
       LEFT JOIN categories 
              ON categories_data.categories_id = categories.id 
                 AND categories.deleted = 0                       -- <<== HERE
WHERE  sites.deleted = 0 
GROUP  BY sites.id 

要进一步了解联接,请访问以下链接:

答案 1 :(得分:1)

只需使用AND

即可
SELECT sites.id, sites.url, GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories
        FROM sites
        LEFT JOIN categories_data ON sites.id = categories_data.sites_id AND categories_data.deleted=0
        LEFT JOIN categories ON categories_data.categories_id = categories.id AND categories.deleted=0
        WHERE sites.deleted=0 GROUP BY sites.id'

答案 2 :(得分:0)

我认为上面已经提到过,但是您也可以在WHERE语句中指定所有这些过滤器。这就是它的样子。

    SELECT sites.id, sites.url, 
    GROUP_CONCAT(categories.name,"|",categories.color SEPARATOR ",") AS categories

    FROM sites
     LEFT JOIN categories_data ON sites.id = categories_data.sites_id 
     LEFT JOIN categories ON categories_data.categories_id = categories.id

    WHERE 
     sites.deleted=0 
     and categories_data.deleted=0
     and categories.deleted=0

    GROUP BY sites.id'

当您遇到错误时,在优化速度和负载之前,以非常标准的格式尝试查询可能会有所帮助。 SELECT ... FROM ... WHERE ... GROUP BY等。