两个表之间的相关子查询

时间:2018-01-17 22:57:35

标签: mysql sql database phpmyadmin

我有两张桌子:

enter image description here

我试图应用相同的逻辑: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'”。我意识到slug字段在projects表中不存在,但示例中的OrderCount字段也不存在。我做错了什么?

1 个答案:

答案 0 :(得分:2)

应该是

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,它是别名,可以是任何名称。