两个表之间的相关子查询

tyu7yeag  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(347)

我有两张table:

我试着用同样的逻辑:http://www.dofactory.com/sql/subquery (最后一个例子)
我想到了这个:

SELECT id, project_name, 
    slug = (SELECT slug 
            FROM project_slugs ps 
            WHERE ps.project_id = p.id 
            ORDER BY created ASC 
            LIMIT 1) 
FROM projects p;

但是,我得到错误“#1054-未知列'slug'在'字段列表'”。我意识到子弹场不存在于 projects 但是table也没有 OrderCount 示例中的字段。我做错什么了?

13z8s7eq

13z8s7eq1#

应该是

SELECT 
   id,
   project_name,
     (SELECT slug FROM 
       project_slugs ps 
       WHERE ps.project_id = p.id 
       ORDER BY created ASC LIMIT 1) as slug 
 FROM projects p;

如果子查询称为slug(别名),则可以是任何名称。

相关问题