简体   繁体   中英

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 !!

A different way of doing it is to order by recipes and then limit to the latest 8, rather than having a subquery :

SELECT cs.chefs_name, rs.recipes_name 
FROM recipes_sa rs
INNER JOIN chefs_sa cs ON rs.recipes_chef = cs.chefs_id 
ORDER BY rs.recipes_name ASC LIMIT 8

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM