Search code examples
mysqlsubqueryinner-join

mysql subquery with inner join and limit


I have two tables recipes_sa with columns:

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

and chefs_sa with columns:

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

And I want to get a limited number of recipes with their chef details, using INNER JOIN and LIMIT

I made the following function:

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];   
            }
        }

And the query is like this

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

But when I run the query I had the following warning:

Warning: PDO::query(): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'recipes_sa.recipes_name' I don't understand why

I have the column recipes_name in recipes_sa table, and from what I read that the database runs the “inner query” (the one with limit) first, then how the recipes_name column is not found !!


Solution

  • You have aliased recipes_sa AS rec. Use the following:

    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