带有内部联接和限制的mysql子查询

时间:2018-09-03 12:11:04

标签: mysql subquery inner-join

我有两个带有列的表recipes_sa

recipes_id   recipes_name   recipes_chef
----------   ------------   ------------

chefs_sa中的列:

chefs_id   chefs_name
--------   ----------

我想使用INNER JOINLIMIT

来获取有限数量的食谱及其厨师详细信息

我做了以下功能:

function getLimitJoinData($data, $tbls, $ids, $abr, $type, $limit) {

            $dataToSelect = implode($data, ',');

            $q = "SELECT $dataToSelect";

            $q.= " FROM (SELECT * FROM $tbls[0] LIMIT $limit) $abr";


            for ($i=1; $i < count($tbls); $i++) { 
                $q .= " ".$type." JOIN ". $tbls[$i] ." ON " . $abr.'.recipes_chef' .' = '. $ids[$i-1][0];   
            }
        }

查询就像这样

SELECT chefs_sa.chefs_name,
       recipes_sa.recipes_name 
FROM (SELECT * FROM recipes_sa LIMIT 8) rec 
INNER JOIN chefs_sa ON rec.recipes_chef = chefs_sa.chefs_id

但是当我运行查询时,出现以下警告:

  

警告:PDO :: query():SQLSTATE [42S22]:找不到列:1054未知列'recipes_sa.recipes_name'   我不明白为什么

我在recipes_name表中有列recipes_sa,据我所知,数据库首先运行“ 内部查询”(有限制的查询),然后运行怎么找不到配方名称列!!

2 个答案:

答案 0 :(得分:3)

另一种方法是按配方排序,然后限制为最新的8,而不是使用子查询:

number = 2

答案 1 :(得分:3)

您已别名recipes_sa AS rec。使用以下内容:

SELECT chefs_sa.chefs_name,
       rec.recipes_name 
FROM (SELECT * FROM recipes_sa LIMIT 8) rec 
INNER JOIN chefs_sa ON rec.recipes_chef = chefs_sa.chefs_id