代码之家  ›  专栏  ›  技术社区  ›  ptrcao

连接查询中的“未知列”错误,该查询旨在选择感兴趣的组中的单行

  •  2
  • ptrcao  · 技术社区  · 7 年前

    我可以知道为什么我会出错吗

    “字段列表”中的未知列“wp_Posteta.post_ID”

    以下是相关表格:

    create table wp_posts (
      ID integer primary key auto_increment,
      post_title varchar(30),
      post_type varchar(30)
    );
    
    create table wp_postmeta (
      ID integer primary key auto_increment,
      post_id integer,
      meta_key varchar(30) not null default '_regular_price',
      meta_value integer not null
    );
    
    insert into wp_posts (post_title, post_type) values
    ('Apple Pie','Product'),
    ('French Toast','Product'),
    ('Shepards Pie','Product'),
    ('Jam Pie','Product'),
    ('Jam Pie','Product'),
    ('Plate','Not a Product'),
    ('Bucket','Not a Product'),
    ('Chequebook','Not a Product'),
    ('French Toast','Product'),
    ('French Toast','Product');
    
    insert into wp_postmeta (post_id, meta_value) values
    (1,10),
    (2,5),
    (3,9),
    (4,8),
    (5,11),
    (6,12),
    (7,10),
    (8,6),
    (9,1),
    (10,1);
    

    以下是查询:

    SELECT wp_postmeta.post_ID, wp_posts.post_title, wp_postmeta.meta_value FROM (
    SELECT wp_posts.post_title, MIN(wp_postmeta.meta_value) AS minprice
    FROM wp_postmeta 
      JOIN wp_posts ON wp_postmeta.post_ID=wp_posts.ID
      WHERE wp_posts.post_type = 'Product'
    GROUP BY wp_posts.post_title
    )
    as x inner join 
    
    (
    SELECT wp_postmeta.post_id, wp_posts.post_title, wp_postmeta.meta_value
    FROM wp_postmeta 
      JOIN wp_posts ON wp_postmeta.post_ID=wp_posts.ID
      WHERE wp_posts.post_type = 'Product'
      ORDER BY wp_posts.post_title, wp_postmeta.meta_value
    )
     as f on x.post_title = f.post_title and f.meta_value = x.minprice
    

    fiddle with data

    如果您感兴趣,我将从 this tutorial 这会让你了解我正在做的事情。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Zaynul Abadin Tuhin    7 年前

    使用子查询时,必须在选择中使用子查询别名

    SELECT f.post_ID, x.post_title, f.meta_value
    FROM (
    SELECT wp_posts.post_title, MIN(wp_postmeta.meta_value) AS minprice
    FROM wp_postmeta 
      JOIN wp_posts ON wp_postmeta.post_ID=wp_posts.ID
      WHERE wp_posts.post_type = 'Product'
    GROUP BY wp_posts.post_title
    )
    as x inner join 
    
    (
    SELECT wp_postmeta.post_id, wp_posts.post_title, wp_postmeta.meta_value
    FROM wp_postmeta 
      JOIN wp_posts ON wp_postmeta.post_ID=wp_posts.ID
      WHERE wp_posts.post_type = 'Product'
      ORDER BY wp_posts.post_title, wp_postmeta.meta_value
    )
     as f on x.post_title = f.post_title and f.meta_value = x.minprice
    

    fiddle demo

    推荐文章