Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从连接表中选择一定数量的行_Php_Mysql_Select_Junction Table - Fatal编程技术网

Php 从连接表中选择一定数量的行

Php 从连接表中选择一定数量的行,php,mysql,select,junction-table,Php,Mysql,Select,Junction Table,我有三张桌子: table1: stores columns:id(PK), name, visits table2: categories columns: id(PK), name table3: cat_store columns: store_id(FK), category_id(FK) 有27个类别,每个商店至少有一个类别。cat_商店是连接台。 我想要实现的是按字母顺序获得所有类别的列表,并在每个类别名称下按名称列出前10个访问的商店。大概是这样的: categories.n

我有三张桌子:

table1: stores
columns:id(PK), name, visits

table2: categories
columns: id(PK), name

table3: cat_store
columns: store_id(FK), category_id(FK)
有27个类别,每个商店至少有一个类别。cat_商店是连接台。 我想要实现的是按字母顺序获得所有类别的列表,并在每个类别名称下按名称列出前10个访问的商店。大概是这样的:

categories.name1
   stores.name1
   stores.name2
   ....
   stores.name10

categories.name2
   stores.name1
   stores.name2
   ....
   stores.name10
...
categories.name27
   stores.name1
   stores.name2
   ....
   stores.name10
目前我有一个包含所有类别名称的数组。然后在foreach循环中,我得到每个类别的存储。这意味着28个查询

有没有办法用更少的查询来实现这一点

提前谢谢! 请原谅我的英语不好。

你的英语很好

您可以使用变量执行此操作,这可能是最有效的方法:

select cs.*
from (select c.name as catname, s.name as storename, s.visits,
             @rn := if(@cid = c.id, @rn + 1, if(@cid := c.id, 1, 1)) as rn
      from cat_store cs join
           categories c
           on cs.category_id = c.id join
           stores s
           on cs.store_id = s.id cross join
           (select @rn := 0, @cid := 0) vars
      order by c.id, visits desc
     ) cs
where rn <= 10;

注意:这会将类别作为单独的列而不是单独的行—这与结果集的表格格式一致。通过使用rn=1逻辑,您可以很容易地在每个组的第一行找到类别。

忘了提到我是MYSQL-PHP的初学者。在phpmyadmin中尝试了您的代码并获得1248-每个派生表都必须有自己的别名。我不理解mysql变量。请询问更多详细信息或介绍教程。@Mirceac21。哎呀。左边是定义变量的子查询的表别名。非常好用。非常感谢,戈登。