0

我有这个 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 ]

那么,我该如何使用WHEREJOIN

谢谢。

4

3 回答 3

2

您不能在联合表WHERE的子句上添加子句。用条件运算符( AND/ORON分隔它们,

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 

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-04-17T16:04:36.920 回答
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'
于 2013-04-17T16:04:44.117 回答
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 等

于 2013-04-17T16:49:23.133 回答