如何使用用户变量为给定列的每个值选择x记录?

时间:2011-02-26 22:58:10

标签: mysql

编辑:我发现只有当我使用phpMyAdmin执行查询时才出现此问题,而不是当我使用PHP的mysql_query()执行相同的查询时。 (我的webhost不提供命令行访问。)具体来说,当在65k +行的表上运行时,phpMyAdmin似乎挂起,但mysql_query()返回预期的结果。


我有一张桌子:产品(product_id,shop_id,date)

对于表中的每个shop_id,以下查询将检索具有最新日期的10行


set @num := 0, @shop_id := NULL;

select shop_id, date from ( select shop_id, date, @num := if(@shop_id = shop_id, @num + 1, 1) as row_number, @shop_id := shop_id as dummy from products order by shop_id, date DESC ) as x where x.row_number <= 10;

例如,如果有10个不同的shop_id,并且每个shop_ids出现在至少10行中,则查询将返回100行,每个shop_id 10个。此查询工作正常。

除了date和shop_id之外,我还想为每一行选择product_id。然而,虽然下面的查询工作正常可以接近55k行,当我尝试65k行时,MySQL似乎无限期挂起(至少phpMyAdmin接口无法返回结果页面):


set @num := 0, @shop_id := NULL;

select product_id, shop_id, date from ( select product_id, shop_id, date, @num := if(@shop_id = shop_id, @num + 1, 1) as row_number, @shop_id := shop_id as dummy from products order by shop_id, date DESC ) as x where row_number <= 10;

我相信我对用户变量的微妙掌握是罪魁祸首,但我无法弄清楚我做错了什么。

0 个答案:

没有答案