简体   繁体   English

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

[英]mysql subquery with inner join and limit

I have two tables recipes_sa with columns: 我有两个带有列的表recipes_sa

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

and chefs_sa with columns: 和带有列的chefs_sa

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

And I want to get a limited number of recipes with their chef details, using INNER JOIN and LIMIT 而且我想使用INNER JOINLIMIT获得有限数量的食谱及其厨师详细信息

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 警告:PDO :: query():SQLSTATE [42S22]:找不到列:1054未知列'recipes_sa.recipes_name'我不明白为什么

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 !! 我在recipes_sa recipes_name中有“ recipes_name recipes_sa ”列, recipes_sa我了解,数据库首先运行“ 内部查询 ”(有限制的查询 ),然后如何找不到“配方名称”列!

A different way of doing it is to order by recipes and then limit to the latest 8, rather than having a subquery : 另一种执行方法是按配方排序,然后限制为最新的8,而不是使用子查询:

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 . 你已经化名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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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