带内连接和限制的mysql子查询
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带内连接和限制的mysql子查询相关的知识,希望对你有一定的参考价值。
我有两个表recipes_sa
列:
recipes_id recipes_name recipes_chef
---------- ------------ ------------
和chefs_sa
列:
chefs_id chefs_name
-------- ----------
我想用他们的厨师细节获得有限数量的食谱,使用INNER JOIN
和LIMIT
我做了以下功能:
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
列,从我读到的数据库首先运行“内部查询”(有限制的那个),然后如何找不到recipes_name列!
答案
你有别名的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
另一答案
另一种方法是按照食谱排序,然后限制为最新的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
以上是关于带内连接和限制的mysql子查询的主要内容,如果未能解决你的问题,请参考以下文章