我有一个表格类别 ( id
, cat_nam
e) 和一个表格食谱 ( id
, cat_id
, recipe_text
)。
现在我想编写一个查询,从每个类别中获取 10 个食谱。
SELECT cat_name, recipe_text
FROM categories c
JOIN recipes r ON c.id=r.cat_id
将获取所有食谱,但我希望每个类别最多 10 个食谱。
(如何)可以用 SQL 查询来完成吗?
SELECT cat_name, recipe_text
FROM
(
SELECT c.cat_name AS cat_name, r.recipe_text AS recipe_text,
@r:=case when @g=c.id then @r+1 else 1 end r,
@g:=c.id
FROM (select @g:=null,@r:=0) n
CROSS JOIN categories c
JOIN recipes r ON c.id = r.cat_id
) X
WHERE r <= 10
SET @num :=0, @cat_id := '';
SELECT recipe_text,cat_name,
@num := if(@cat_id = cat_id, @num + 1, 1) as row_number,
@cat_id := cat_id as cat_id
FROM recipes r
JOIN categories c ON c.id = r.cat_id
group by cat_name,recipe_text
having row_number <= 10
这对你有用...
SET @rank = 0;
SELECT cat_name,recipe_text FROM (SELECT
id,cat_id AS P,recipe_text,
CASE
WHEN @rowdata != pid
THEN @rank := 0 & @rowdata := cat_id
ELSE @rank := @rank + 1
END AS rank
FROM
recipes
GROUP BY cat_id,
id
) X ,t
WHERE X.rank <= 3 AND X.p = t.cat_id;
你可以试试下面的代码
function recipe($cat_id='',$new_ar=array())
{
if($cat_id!="")
{
$new_ar1=array();
$db="select recipe_text from recipes where cat_id=".$cat_id." order by cat_id limit 10";
$sq=mysql_query($db);
while($fe=mysql_fetch_object($sq))
{
array_push($new_ar1,$fe->recipe_text);
}
return $new_ar1;
}
else
{
$db="select id,cat_name from categories order by id";
$sq=mysql_query($db);
while($fe=mysql_fetch_object($sq))
{
array_push($new_ar,$fe->cat_name);
$new_ar[$fe->id]=array($fe->cat_name);
array_push($new_ar[$fe->id],recipe($fe->id,$new_ar));
}
}
}
recipe();
it will give output like below
Array
(
[0] => cat 1
[1] => Array
(
[0] => cat 1
[1] => Array
(
[0] => rice
[1] => curry
[2] => mutton
[3] => A recipe
[4] => B recipe
[5] => C recipe
[6] => D recipe
[7] => E recipe
[8] => F recipe
[9] => G recipe
)
)
[2] => Array
(
[0] => cat 2
[1] => Array
(
[0] => dal
[1] => fish
)
)
[3] => Array
(
[0] => cat 3
[1] => Array
(
)
)
[4] => Array
(
[0] => cat 4
[1] => Array
(
)
)
)
Thanks
Ripa Saha
试试下面的 SQL
select
cat_name,
recipe_text
from categories as c,recipes as r
where c.id=r.cat_id limit 10
我们最后做了一个存储过程:
DELIMITER $$
CREATE PROCEDURE `test`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE cur_id INT;
DECLARE cur CURSOR FOR
SELECT id FROM category;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
CREATE TABLE tmp(catname VARCHAR(255), recipeId INT);
OPEN cur;
the_loop: LOOP
FETCH cur INTO cur_id;
IF done THEN
LEAVE the_loop;
END IF;
INSERT INTO tmp(catname, recipeId)
SELECT catname, recipeId
FROM category c LEFT JOIN recipes r ON c.id=r.cat_Id
WHERE c.id=cur_id
LIMIT 0, 10;
END LOOP;
SELECT * FROM tmp;
DROP TABLE tmp;
END