使用多个连接的未知列

时间:2018-01-16 11:58:41

标签: mysql sql wordpress

我试图连接两张桌子两次。一个有不同的行,另一个时间用于不同的行,但我得到以下错误,

#1054 - Unknown column 'p1.ID' in 'on clause'

MySQL的:

SELECT p1.ID, p1.post_title, p1.post_excerpt, p2.meta_value, p1.guid, p4.guid
FROM wp_posts AS p1, wp_postmeta AS p3
    INNER JOIN wp_postmeta p2
        ON p1.ID = p2.post_id 
        AND p2.meta_key = '_price'
        AND p1.post_type = 'product'
        AND p1.post_status = 'publish'
    INNER JOIN wp_posts p4
        ON p4.ID = p3.post_id 
        AND p3.meta_key = '_thumbnail_id'
        AND p4.post_type = 'attachment'

编辑:下面是我在答案后所做的查询,但它给了我一张空表。

SELECT p1.ID, p1.post_title, p1.post_excerpt, p2.meta_value, p1.guid, p3.guid
FROM wp_posts p1 
     JOIN wp_postmeta p2
     ON p1.ID = p2.post_id AND
        p2.meta_key = '_price' AND
        p1.post_type = 'product' AND
        p1.post_status = 'publish' 
     JOIN wp_posts p3
     ON p3.ID = p2.post_id AND 
        p2.meta_key = '_thumbnail_id' 
     JOIN wp_postmeta p4
     ON p4.post_id = p3.ID AND
        p3.post_type = 'attachment';

2 个答案:

答案 0 :(得分:2)

从不FROM子句中使用逗号。 始终使用显式JOIN语法。您的问题是一个范围问题并且很容易修复。

执行此操作时,您会注意到p3id上的post_id似乎缺少加入条件。这是您想要的查询结构:

SELECT p1.ID, p1.post_title, p1.post_excerpt, p2.meta_value, p1.guid, p4.guid
FROM wp_posts p1 JOIN
     wp_postmeta p2
     ON p1.ID = p2.post_id AND
        p2.meta_key = '_price' AND
        p1.post_type = 'product' AND
        p1.post_status = 'publish' JOIN
     wp_posts p3
     ON p3.? = p2.? AND  -- What join condition do you intend here?
        p3.meta_key = '_thumbnail_id' JOIN
     wp_postmeta p4
     ON p4.ID = p2.post_id AND
        p4.post_type = 'attachment';

答案 1 :(得分:0)

  

#1054 - 'on clause'中的未知列'p1.ID'

根据JOIN Syntax 的文档:

  

JOIN的优先级高于逗号运算符(,),因此连接   表达式t1,t2 JOIN t3被解释为(t1,(t2 JOIN t3)),而不是   ((t1,t2)JOIN t3)。这会影响使用ON子句的语句   因为该子句只能引用操作数中的列   加入,优先级会影响对那些操作数的解释   是。

     

示例

SELECT * FROM t1, t2 JOIN t3 ON (t1.i1 = t3.i3);
     

JOIN优先于逗号运算符,因此操作数为   ON子句是t2和t3。因为t1.i1不是任何一列   对于操作数,结果是'on'中的未知列't1.i1'   条款'错误。

因此相应地更改了join子句并构造了sql语句。