"从"多个表然后" LEFT JOIN"另一张桌子

时间:2018-03-12 09:15:34

标签: mysql

我的查询效果非常好:

SELECT node.id, CONCAT( REPEAT( '       ', (COUNT(parent.name_en) - 1) ), node.name_en) AS name_en_spaced, node.name_en as name_en, node.name_ar as name_ar, node.rgt as rgt,node.lft as lft, node.filter as filter
    FROM category AS node,
        category AS parent
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
    GROUP BY node.id
    ORDER BY node.lft

当我添加LEFT JOIN时(我只是这样做,以了解product表中是否有与特定category相关的记录,无论它们是什么或有多少:< / p>

SELECT p.price,node.id, CONCAT( REPEAT( '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', (COUNT(parent.name_en) - 1) ), node.name_en) AS name_en_spaced, node.name_en as name_en, node.name_ar as name_ar, node.rgt as rgt,node.lft as lft, node.filter as filter
    FROM category AS node,
        category AS parent
    LEFT JOIN product AS p on node.id = p.category_id
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
    GROUP BY node.id
    ORDER BY node.lft

我收到此错误#1054 - Unknown column 'node.id' in 'on clause'这令人困惑。可以帮帮我!

2 个答案:

答案 0 :(得分:0)

您正在混合两种写连接方式。在我看来,最好总是指定你的联接,因为它更容易阅读:

SELECT p.price,node.id,
 CONCAT( REPEAT( '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', (COUNT(parent.name_en) - 1) ), node.name_en) AS name_en_spaced,
 node.name_en as name_en,
 node.name_ar as name_ar,
 node.rgt as rgt,
 node.lft as lft, 
 node.filter as filter
FROM category AS node,
LEFT JOIN category AS parent
   ON node.lft BETWEEN parent.lft AND parent.rgt
    AND node.XXX = parent.XXX
LEFT JOIN product AS p on node.id = p.category_id
GROUP BY node.id
ORDER BY node.lft

答案 1 :(得分:0)

您正在混合两种类型的连接(交叉和左侧)。试试这个:

SELECT p.price,node.id, CONCAT( REPEAT( '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', (COUNT(parent.name_en) - 1) ), node.name_en) AS name_en_spaced, node.name_en as name_en, node.name_ar as name_ar, node.rgt as rgt,node.lft as lft, node.filter as filter
    FROM category AS node
    LEFT JOIN category AS parent ON node.id = parent.id
    LEFT JOIN product AS p on node.id = p.category_id
    WHERE node.lft BETWEEN parent.lft AND parent.rgt
    GROUP BY node.id
    ORDER BY node.lft